简体   繁体   English

如何在自定义指令中使用属性绑定?

[英]How to use property binding in custom directive?

Directive :指令

// highlight.directive.ts 
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective {
  @Input() yourColor: any = 'red';
  constructor(private el: ElementRef) {
    el.nativeElement.style.backgroundColor = this.yourColor;
  }
}

Consumer :消费者

// app.component.html
<div appHighlight [yourColor]="'blue'">Testing</div>

Result :结果

在此处输入图片说明

Question

Why can't I pass blue to yourColor ?为什么我不能将blue传递给yourColor

You should move your code from constructor to ngOnInit .您应该将代码从constructor移动到ngOnInit Use constructor in Angular only for injecting dependencies, but ngOnInit for executing a code when component is mounted. Angular 中的constructor仅用于注入依赖项,但ngOnInit用于在安装组件时执行代码。

Here is more info about that: Difference between Constructor and ngOnInit以下是更多信息: Constructor 和 ngOnInit 之间的差异

Here is a solution using two-way binding:这是使用双向绑定的解决方案:

 // highlight.directive.ts
 export class HighlightDirective {
        yourColor: any = 'red';

        ngOnInit() {
       // change color in method
         this.yourColor = ‘blue’;
         }
       
       }

  // app.component.html
  <div appHighlight style=“background-color=    {{yourColor}}”>Testing</div>

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

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