Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Angular 2+;中的自定义指令中读取/获取元素属性;_Angular_Angular2 Directives - Fatal编程技术网

从Angular 2+;中的自定义指令中读取/获取元素属性;

从Angular 2+;中的自定义指令中读取/获取元素属性;,angular,angular2-directives,Angular,Angular2 Directives,我正在构建一个自定义指令,希望在其中读取本机元素的一个属性(formControlName),然后有条件地向元素添加一个或多个属性 但是,当I console.log本机元素的属性时,我得到: 未定义 以下是我尝试过的: @Directive({ selector: '[appInputMod]' }) export class InputModDirective implements OnInit { constructor(public renderer: Renderer2, p

我正在构建一个自定义指令,希望在其中读取本机元素的一个属性(formControlName),然后有条件地向元素添加一个或多个属性

但是,当I console.log本机元素的属性时,我得到:

未定义

以下是我尝试过的:

@Directive({
  selector: '[appInputMod]'
})
export class InputModDirective implements OnInit {

  constructor(public renderer: Renderer2, public hostElement: ElementRef) { }

  @Input()
  appInputMod() { }

  ngOnInit() {

    console.log(this.hostElement.nativeElement.formcontrolname);

    const el = this.hostElement.nativeElement;
    if (el.formcontrolname === 'firstName')
    {
        this.renderer.setAttribute(this.hostElement.nativeElement, 'maxlength', '35');
    }
  }
}

如何从指令中读取此属性名称?

这是一个技巧,但可能是一个有用的旁注:

这项工作来自ngOnInit:

this.hostElement.nativeElement.getAttribute('formcontrolname');

您正在做的事情看起来不是很有角度,您通常不希望开始依赖DOM操作。更具角度的方法是将指令元素上的属性读取为
@Input()
,并将结果提供为
@Output()

@指令({
选择器:“[appInputMod]”
})
导出类InputModDirective实现OnInit{
@Input()formcontrolname:字符串;
@Output()发生了一些事情:EventEmitter=neweventemitter();
构造函数(公共呈现器:Renderer2,公共hostElement:ElementRef){}
恩戈尼尼特(){
如果(formcontrolname=='firstName'){
emit({maxlength:35});
}
然后在模板中:

<some-element appInputMod formcontrolname="myName" (somethingHappened)="doSomething($event)">
</some-element>


尝试
ngAfterViewInit
而不是
ngOnInit
我得到了相同的结果。当你在浏览器中检查标签时,formControlName属性是否出现在标签上?顺便说一句,也许你应该使用正确的方法来获取属性。是的,我想这就是我要问的。请看我的答案。
<some-element appInputMod formcontrolname="myName" (somethingHappened)="doSomething($event)">
</some-element>