Browse Source

@directive Exports as 用法

用以取得自訂按紐指令實體
master
HarveyChou 2 years ago
parent
commit
44795b7dfc
  1. 3
      src/app/app.component.html
  2. 11
      src/app/app.component.ts
  3. 6
      src/app/custom-button.directive.ts

3
src/app/app.component.html

@ -1,2 +1,5 @@
<button type="button">一般按鈕</button>
<button type="button" appCustomButton>套用指令的按鈕</button>
<button type="button" #button="customButton" appCustomButton>
套用指令的按紐
</button>

11
src/app/app.component.ts

@ -1,8 +1,15 @@
import { Component } from '@angular/core';
import { CustomButtonDirective } from './custom-button.directive';
import { Component, ViewChild, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {}
export class AppComponent implements OnInit{
@ViewChild('button',{static:true}) button!:CustomButtonDirective;
ngOnInit(): void {
this.button.changeColor('red');
}
}

6
src/app/custom-button.directive.ts

@ -2,6 +2,7 @@ import { Directive, ElementRef, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[appCustomButton]',
exportAs:'customButton',
})
export class CustomButtonDirective implements OnInit {
constructor(private elRef: ElementRef, private renderer: Renderer2) {}
@ -11,4 +12,9 @@ export class CustomButtonDirective implements OnInit {
this.renderer.setStyle(this.elRef.nativeElement, 'fontSize', '14pt');
this.renderer.setStyle(this.elRef.nativeElement, 'fontWeight', 'bold');
}
changeColor(color:string): void{
this.renderer.setStyle(
this.elRef.nativeElement, 'color', color
);
}
}
Loading…
Cancel
Save