[英]angular - how to get a reference of a directive which has no exportAs
clrDate is a custom third party directive without an exportAs statement. clrDate 是没有 exportAs语句的自定义第三方指令。
source code源代码
@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')
...
}
I want to be able to get a reference to it from inside my controller as well as my customDirective.我希望能够从我的 controller 以及我的 customDirective 中获得对它的引用。 How can I do that?我怎样才能做到这一点?
<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>
Add #ref
(template variable) on the directive and you can get it in the component在指令上添加#ref
(模板变量),即可在组件中获取
Depending on from where you want to access the directive instance, you should be able to get hands on it via @ViewChild
or constructor injection.根据您要从哪里访问指令实例,您应该能够通过@ViewChild
或构造函数注入来获得它。
From your controller (component) or from your customDirective you should be able to do following:从您的 controller (组件)或您的 customDirective 中,您应该能够执行以下操作:
// will be available in ngOnInit
@ViewChild(ClrDateInput, { static: true })
clrDateDirective: ClrDateInput;
assuming you can have multiple ClrDateInput
directives you could use @ViewChildren
:假设您可以有多个ClrDateInput
指令,您可以使用@ViewChildren
:
// will be available in ngAfterViewInit
@ViewChildren(ClrDateInput)
clrDateDirectives: QueryList<ClrDateInput>;
from the host element of the directive itself you can inject the directive via constructor injection:从指令本身的宿主元素中,您可以通过构造函数注入来注入指令:
// 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) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.