如何在子組件的觀察輸入更改時調用父組件的函數?如何觀察ng內容中的輸入元素更改
以下是HTML結構。
# app.comopnent.html
<form>
<textbox>
<input type="text">
</textbox>
</form>
# textbox.component.html
<div class="textbox-wrapper">
<ng-content>
</div>
限制如下。
- TextboxComponent has
ng-content
and need to projectinput
element to it。 - 當輸入
input
元素時,在文本框組件中發出事件。 - 不想讓
input
元素擁有更多屬性,例如<input type="text" (input)="event()">
。
我在寫代碼,但不能找到解決的辦法......
# input.directive.ts
@Directive({ selector: 'input', ... })
export class InputDirective {
ngOnChanges(): void {
// ngOnChanges() can observe only properties defined from @Input Decorator...
}
}
# textbox.component.ts
@Component({ selector: 'textbox', ... })
export class TextboxComponent {
@ContentChildren(InputDirective) inputs: QueryList<InputDirective>;
ngAfterContentInit(): void {
this.inputs.changes.subscribe((): void => {
// QueryList has a changes property, it can observe changes when the component add/remove.
// But cannot observe input changes...
});
}
}
爲什麼你不希望使用的輸出綁定,如?你怎麼能確定其他開發者(甚至你)只將輸入元素添加到TextboxComponent的標記中? – rrjohnson85
因爲我應該在'input'元素上附加一個輸出綁定,如果我想使用它,它會很冗長。但是我可以在InputDirective中使用'host:{(input):'event()'}'屬性。 最大的問題是使用'ng-content'的TextboxComponent可以檢測InputDirective什麼時候輸入了什麼。 –