angular 在指令里把组件当服务,并订阅组件的事件

2020-06-16 14:22:55 浏览数 (1)

代码语言: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>();
}
- ...

0 人点赞