Come chiamare la funzione del componente genitore quando il componente figlio ha osservato le modifiche di input?Come osservare le modifiche degli elementi di input in ng-content
Quanto segue è una struttura HTML.
# app.comopnent.html
<form>
<textbox>
<input type="text">
</textbox>
</form>
# textbox.component.html
<div class="textbox-wrapper">
<ng-content>
</div>
Le restrizioni sono come segue.
- TextboxComponent ha
ng-content
e deve proiettare l'elementoinput
. - Emettere un evento in TextboxComponent quando l'elemento
input
immette qualcosa. - Non voglio rendere l'elemento
input
più attributi, ad es.<input type="text" (input)="event()">
.
stavo scrivendo il codice, ma non riesco a trovare una soluzione ...
# 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...
});
}
}
Perché non si desidera utilizzare un'uscita vincolante, come ? Come puoi essere sicuro che altri sviluppatori (o anche tu) aggiungano solo elementi di input al markup di TextboxComponent? – rrjohnson85
Perché dovrei aggiungere un'associazione di output all'elemento 'input' ed è prolissa se voglio usarla. Ma posso usare 'host: {(input): 'event()'}' proprietà in InputDirective. Il problema più grande è che TextboxComponent che usa 'ng-content' può rilevare quando InputDirective è stato immesso in input. –