繁体   English   中英

如何使用 Angular Directive 在 HTML 文本框元素中设置默认值。 请参考以下代码

[英]How to set the default value inside a HTML Text box element using Angular Directive . Please refer the below code

下面的代码适用于更改“div,标题标签”的innerHTML,但不适用于文本框

@Component({
  selector: 'app-root',
  template: ` <h3 appNamevalidation >Angular 7 Template-Driven Form Validation</h3>
  <input type = "text" [(ngModel)]="model.firstName" #firstName="ngModel" required appNamevalidation 
  />`
})

@Directive({
  selector: '[appNamevalidation]'
})

export class NamevalidationDirective {
  constructor(private elem: ElementRef) { }

  ngOnInit() {
    console.log(' inside ngOninIt directive hook');
    this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
    this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
  }
}

你的指令的ngOnInit钩子在你的输入绑定你的ngModel之前被执行。 您可以使用另一个 Lifecycle 挂钩(如ngAfterViewChecked来使其工作:

export class NamevalidationDirective {
    constructor(private elem: ElementRef) { }

    ngAfterViewChecked() {
        this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
        this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
    } 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM