在角度2中,如果我看到<element [x]='' ..>
,我怎么知道x是一个导致单向数据绑定的指令(例如[ngClass]或[nyStyle]),或者它是一个应用于此标记的Angular组件的输入(组件配置中的输入)?
I don't think that you can distinguish them by some coding technique, but
if you just want to find out what this [x]
is doing here ? then
There are three things that it might be doing there
1. It's an Angular Directive eg: [ngModel]
[ngIf]
2. It's a Custom Directive eg: [directiveToConsoleLogTheContentOfAnInputField]
3. It's just an Input/Output property or ( [oneWay]/ [(twoWay)] binding) for <element>
component.
<element>
component's .ts file and see if it's one of the input or output properties. Update: For more details see @MarkRajcok's answer. (Yes, I don't think that I know better.)
The syntax is ambiguous (if you're just reading the HTML template), which is something I don't like. I've asked about this previously (no answers yet): Why does simply [myHighlight]="..." work for an attribute directive?
Assuming [x]
is not [style.x]
or [attr.x]
, then I believe [x]="..."
always indicates an input property databinding. It gets a bit tricky because if the input property is defined on a directive/component that uses an attribute selector and it has the same name ( x
), then it is a shorthand for: x [x]="..."
. (I don't like the shorthand syntax, but I can't say I like the longhand syntax much, which does work, FYI.)
In other words, when Angular sees/parses [x]="..."
it checks to see if
x
available to the current view '[x]'
x
too If the above are true, then it uses the directive/component.
If the above is not true, then it looks to see if the element
has a property with the name x
. If it doesn't we get that familiar Can't bind to 'x' since it isn't a known native property
error.
The fact that Angular does the 2 (or 3) step checking means that the syntax is ambiguous, hence we have to mentally perform the same steps to determine what is really happening. And this, my friends, is why I don't like it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.