When to use square brackets [ ] in directives @Inputs and when not?

前端 未结 4 1530
猫巷女王i
猫巷女王i 2020-12-02 14:16

I\'m confused a little.

See this simple directive:

 @Directive({
      selector: \'[myDirective]\'
    })
    export class MyDirective {

      priva         


        
4条回答
  •  暖寄归人
    2020-12-02 14:32

    If you write it means that the right-hand side heroImageUrl is a template expression.

    The simple difference between [myText]="abc" and myText="abc" is that in former you are asking angular to set the target PROPERTY myText using the template expression abc, while in the latter you setting the target property called myText using the string 'abc'.

    Let's understand a little more about HTML.

    In HTML you can define an element like this.

    
    

    input is an element whose attributes are type and value. When your browser parses this, it will create a DOM entry (an object) for this element. The DOM entry will have some properties like align, baseURI, childNodes, children etc. So, that's the difference between HTML attributes and DOM properties See reference. Sometimes the attribute and property have same names which causes confusion. For above input tag, it has the attribute value = Bob and also has a property value that will have the value of whatever you type in the text box. In summary, attribute is what you define about the tag, and property is what gets generated in the DOM tree.

    In the world of Angular, the only role of attributes is to initialize element and possibly directive state. When you write a data binding, you're dealing exclusively with properties and events of the target object. HTML attributes effectively disappear.

    So to summarize, in

    you essentially are saying that:

    1. apply the directive myDirective to my div element.
    2. bind the variable myEnabled to the expression on the right. The expression says true, so the value of myEnabled is true.
    3. bind the variable myText to the expression on the right. The expression says abc. Is there any abc defined? No, so the expression evaluated to undefined.

提交回复
热议问题