gpt4 book ai didi

angular - 在 Angular Directive(指令)组件之外调用函数

转载 作者:行者123 更新时间:2023-12-04 01:20:03 24 4
gpt4 key购买 nike

有没有办法在我的指令中调用函数,但在组件之外?

例子:

<ion-input #bar barcodeScanner></ion-input>
<button (click)="bar.start()" type="button">
<i class="my-icons-scaner"></i>
</button>

指令:

@Directive({
selector: '[barcodeScanner]'
})
export class BarcodeScannerDirective implements OnInit {

constructor(private _element: ElementRef) {}

ngOnInit() {
const element = this._element.nativeElement
console.log({ element })
}

public start(){
console.log('start?')
}

}

最佳答案

像这样在 Directive 装饰器上使用 exportAs 属性

Defines the name that can be used in the template to assign thisdirective to a variable.

directive.ts

@Directive({
selector: '[barcodeScanner]',
exportAs: 'barcodeScanner'
})

然后我们可以在模板中的任何地方访问我们的 barcodeScanner 实例:

<ion-input #bar="barcodeScanner" barcodeScanner></ion-input>
<button (click)="bar.start()" type="button">
<i class="my-icons-scaner"></i>
</button>

关于angular - 在 Angular Directive(指令)组件之外调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62777180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com