Я пытался заставить ContentChild с директивой работать в демо / примере, и я продолжаю сталкиваться с директивой, не работающей. Ошибок не выбрасывается. Я скопировал сценарий на StackBlitz, и у меня та же проблема: https://stackblitz.com/edit/angular-contentchild-directive-etktcd
Почему я все еще получаю "undefined" для дочернего ввода?
Вот директива:
import { Component, Directive, Input, ContentChild, OnInit, OnDestroy, forwardRef, AfterContentInit} from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { FocusDirective } from '../directive/focus.directive';
@Component({
selector: 'field-validation',
template: `
<ng-content></ng-content>
`
})
export class FieldValidationComponent implements OnInit, AfterContentInit {
@ContentChild(FocusDirective) input: FocusDirective;
ngOnInit(): void {
console.log("ngOnInit::input is: ", this.input);
// this.input.focusChange.subscribe((focus) => {
// this.updateAttributes();
// });
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.input);
}
}
Вот дочерний компонент:
import { Component, Directive, Input, ContentChild, OnInit, OnDestroy,
forwardRef, AfterContentInit} from '@angular/core';
import { AbstractControl } from '@angular/forms';
import { FocusDirective } from '../directive/focus.directive';
@Component({
selector: 'field-validation',
template: `
<ng-content></ng-content>
`
})
export class FieldValidationComponent implements OnInit, AfterContentInit {
@ContentChild(FocusDirective) input: FocusDirective;
ngOnInit(): void {
console.log("ngOnInit::input is: ", this.input);
// this.input.focusChange.subscribe((focus) => {
// this.updateAttributes();
// });
}
ngAfterContentInit(): void {
console.log("ngAfterContentInit::input is: ", this.input);
}
}
Вот HTML-код в родительском приложении:
<form [formGroup]="testForm">
<field-validation>
<input type="text" placeholder="0.00">
</field-validation>
<div>
<button type="submit">FAKE SUBMIT</button>
</div>
</form>