在使@ContentChild与指令配合使用时遇到问题

时间:2019-06-29 03:32:31

标签: angular7 angular2-directives angular8

我一直试图在演示/示例中使ContentChild与Directive一起工作,但我一直遇到无法使用的指令。没有错误被抛出。我已经在StackBlitz上复制了该方案,并且遇到了相同的问题:https://stackblitz.com/edit/angular-contentchild-directive-etktcd

为什么对于子输入我仍然得到“未定义”?

这是指令:

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>

1 个答案:

答案 0 :(得分:1)

请将FocusDirective类添加到declaration的{​​{1}}属性中,如下所示。

AppModule