【问题标题】:angular - how to get a reference of a directive which has no exportAs角度 - 如何获取没有 exportAs 的指令的引用
【发布时间】:2019-10-15 07:40:42
【问题描述】:

clrDate 是一个自定义的第三方指令没有 exportAs 语句。

源代码

@Directive({
  selector: '[clrDate]',
  host: {
    '[class.clr-input]': 'true',
  },
  providers: [DatepickerFocusService],
})
export class ClrDateInput extends WrappedFormControl<ClrDateContainer> implements OnInit, AfterViewInit, OnDestroy {
  @Input() placeholder: string;
  @Output('clrDateChange') dateChange: EventEmitter<Date> = new EventEmitter<Date>(false);
  @Input('clrDate')
...
}

我希望能够从我的控制器以及我的 customDirective 中获取对它的引用。我该怎么做?

<clr-date-container customDirective>
    <label for="dateControl">Requirement Date</label>
    <input id="dateControl" type="date" [placeholder]="'TT.MM.YYYY'" [(clrDate)]="item.requirementDate" (clrDateChange)="onChange($event)" [ngModel]="null" name="requirementDate"/>
    <clr-control-error>{{ 'FORMS.VALIDATION.DATE_INVALID' | translate }}</clr-control-error>
</clr-date-container>

【问题讨论】:

    标签: angular angular-directive vmware-clarity


    【解决方案1】:

    在指令上添加#ref(模板变量)即可在组件中获取

    【讨论】:

    • 你的意思是来自我的“customDirective”的本地参考?但我希望能够反过来获得参考。
    【解决方案2】:

    根据您要从哪里访问指令实例,您应该能够通过@ViewChild 或构造函数注入来获得它。

    从您的控制器(组件)或您的 customDirective 中,您应该能够执行以下操作:

      // will be available in ngOnInit
      @ViewChild(ClrDateInput, { static: true })
      clrDateDirective: ClrDateInput;
    

    假设您可以有多个 ClrDateInput 指令,您可以使用 @ViewChildren

      // will be available in ngAfterViewInit
      @ViewChildren(ClrDateInput)
      clrDateDirectives: QueryList<ClrDateInput>;
    

    从指令本身的宿主元素中,您可以通过构造函数注入来注入指令:

    // app.component.html
    <custom-app ctrlDate></custom-app>
    
    // custom-app.component.ts
    @Component({
      selector: "custom-app",
      template: `
        <h2>Custom App</h2>
      `
    })
    class CustomAppComponent {
        constructor(@Self() private ClrDateInput: ClrDateInput) {}
    

    你可以看一个例子sandbox

    【讨论】:

    • 所以@ViewChild 可以使用它们的类从组件的模板中选择任何指令?您是否还有关于如何从位于该父元素上的指令访问指令的建议?
    • 我认为你应该能够在没有 @Self() 装饰器的情况下注入它。
    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 2021-08-26
    • 2017-12-19
    • 2018-08-05
    • 2018-07-12
    • 2019-06-19
    • 2017-10-02
    相关资源
    最近更新 更多