【问题标题】:How to call Angular Component Method Outside of Angular Library using @ViewChild()?如何使用 @ViewChild() 在 Angular 库之外调用 Angular 组件方法?
【发布时间】:2019-02-21 12:31:44
【问题描述】:

我有 angular 库,带有公开组件调用 AComponent。 AComponent 具有模板以及一组方法和属性。一旦 Angular 库被打包,它就会作为 nuget 包公开,以便其他项目可以使用它。

@Component({
  selector: 'xxx-editor',
  templateUrl: './xxx.component.html',
  styleUrls: ['./xxx.component.scss'],
})
export class AComponent implements OnInit {
......
......

 logToConsole() {
        console.log('trace for working');
 }

}

我有一个新要求,因此为了满足该要求,我想将 AComponent 中的方法之一 logToConsole 公开给外部,以便依赖方可以使用该组件调用该方法.

会说这个库被 BComponent 使用并在 *.ts 文件中作为 ViewChild 访问

BComponent - 模板

 <div style="text-align:center">
      <h1>
        Welcome to {{ title }}!
      </h1>
      <xxx-editor #xxxEditor [(ngModel)]="html" [editable]="true"
                        ></xxx-editor>

    </div>

BComponent - Ts

 @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      ngOnInit(): void {
        this.editor.logToConsole();
      }
      title = 'editor-test';

      html = 'sample test data';

      @ViewChild('xxxEditor') editor: AComponent | null;
    }

问题是 this.editor.logToConsole() logToConsole 未定义。它是如何设计角度库的?无论如何我可以访问此方法吗?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这是因为 ngOnInit() 生命周期方法在 Angular 渲染 DOM 之前被调用。您应该在 ngAfterViewInit() 中调用该方法,该方法会在视图呈现后被调用。

    ngAfterViewInit(): void {
       this.editor.logToConsole();
    }
    

    Angular 文档 - 说明

    ngOnInit

    在 Angular 首次显示后初始化指令/组件 数据绑定属性并设置指令/组件的输入属性。

    ngAfterViewInit

    Angular初始化组件的视图和子视图后响应/ 指令所在的视图。

    【讨论】:

      猜你喜欢
      • 2021-04-12
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2019-03-03
      • 2018-10-28
      • 2019-10-14
      相关资源
      最近更新 更多