代码语言:typescript复制
- Module
import { ExampleDirective , TabBodyComponent} from './example.component';
@NgModule({
declarations: [ExampleDirective , TabBodyComponent],
providers: [ TabBodyComponent ]
})
export class ExampleModule { }
AppComponent
@Component({
selector: 'app-component',
template: `
<tab-body example></tab-body>
`
})
export class AppComponent{}
* ExampleComponent ,TabBody 在一个文件里,下面注入时用 forwardRef
import { Subscription } from 'rxjs';
@Directive({
selector: 'example, [example]'
})
export class ExampleDirective implements OnInit, OnDestroy {
constructor(@Inject(forwardRef(() => TabBody)) private _host: TabBody) {}
private _centeringSub = Subscription.EMPTY;
ngOnInit(): void {
this._centeringSub = this._host._beforeCentering
.pipe()
.subscribe((isCentering: boolean) => {
console.log(isCentering) // _beforeCentering.emit(true) 传的值 true;
});
}
ngOnDestroy() {
this._centeringSub.unsubscribe();
}
}
* TabBodyComponent
@Component({
selector: 'tab-body',
template: `
<span (click)="_beforeCentering.emit(true)">点击触发事件,指令subscribe</span>
`
})
export class TabBodyComponent{
@Output() readonly _beforeCentering: EventEmitter<boolean> = new EventEmitter<boolean>();
}
- ...