检测组件是否在Angular 2中设置了NgModel

时间:2016-09-20 21:37:40

标签: angular angular2-template angular2-forms

我想知道某个组件是否设置了[(ngModel)]

我正在创建一个预先输入组件,并想知道ngModel是否设置为该元素。

这样的事情:

MY-form.component.html

...
<my-custom-typeahead [(ngModel)]="somevariable" name="someinput1"><my-custom-typeahead>

<my-custom-typeahead name="someinput2"><my-custom-typeahead>
...

MY-定制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不是答案,但这是我可以解释它的方式。

1 个答案:

答案 0 :(得分:1)

如果要实施[(ngModel)],则必须实施其接口ControlValueAccessor

此界面具有writeValue(val: any) ..

功能

如果调用此函数,则会通过[(ngModel)]收到一个值。 :)