检测组件是否在 Angular 中设置了 NgModel 2
Detect if component has NgModel set in Angular 2
我想知道某个组件是否设置了 [(ngModel)]
。
我正在创建一个 typeahead 组件,想知道 ngModel 是否设置为该元素。
像这样:
我的-form.component.html
...
<my-custom-typeahead [(ngModel)]="somevariable" name="someinput1"><my-custom-typeahead>
<my-custom-typeahead name="someinput2"><my-custom-typeahead>
...
我的自定义-typeahead.component.ts
@ngModule({
...
selector: 'my-custom-typeahead',
...
})
export class myCustomTypeaheadComponent{
// I would like to know if the ngModel was set in the component
// something like @Host('my-custom-typeahead').has2wdb('ngModel')
}
我认为使用@Host 不是答案,但这是我可以解释得更多的方式。
如果你想实现[(ngModel)]
你必须实现它的接口ControlValueAccessor
。
这个接口有函数writeValue(val: any)
..
如果调用此函数,您将通过 [(ngModel)]
收到一个值。 :)
我想知道某个组件是否设置了 [(ngModel)]
。
我正在创建一个 typeahead 组件,想知道 ngModel 是否设置为该元素。
像这样:
我的-form.component.html
...
<my-custom-typeahead [(ngModel)]="somevariable" name="someinput1"><my-custom-typeahead>
<my-custom-typeahead name="someinput2"><my-custom-typeahead>
...
我的自定义-typeahead.component.ts
@ngModule({
...
selector: 'my-custom-typeahead',
...
})
export class myCustomTypeaheadComponent{
// I would like to know if the ngModel was set in the component
// something like @Host('my-custom-typeahead').has2wdb('ngModel')
}
我认为使用@Host 不是答案,但这是我可以解释得更多的方式。
如果你想实现[(ngModel)]
你必须实现它的接口ControlValueAccessor
。
这个接口有函数writeValue(val: any)
..
如果调用此函数,您将通过 [(ngModel)]
收到一个值。 :)