如何在Angular中替换和附加组件的视图?

时间:2019-11-19 11:55:10

标签: angular angular8 angular-components

因此,我使用此代码将一些HTML代码渗透到我的应用程序中:

fetchDashboard() {
    const requestOptions: Object = {
      headers: new HttpHeaders().append('Authorization', 'Bearer <tokenhere>'),
      responseType: 'text'
    }
    this.http.get<string>('http://localhost:3000/avior/dashboard',
        requestOptions)
            .subscribe(response => {
                   // replace me with modification of component view
                   console.log(response);
            }
    );
}

我在视图中使用<a class="dropdown-item" (click)=fetchDashboard()>Dashboard</a>

执行此代码

为获得最佳解决方案:

  • 如何替换和附加到某个组件的视图(由于该视图包含多个组件)?

可选问题:

  • 有没有一种方法可以直接附加到DOM?由于Angular不 正确使用听起来不可行的DOM,因此是可选的。

2 个答案:

答案 0 :(得分:1)

尝试这样:

.ts

.subscribe(response => {
     this.aComponentData = response;
}

view.html:

<a-component [data]="aComponentData"></a-component>

<b-component></b-component>

a.component.ts

@Input() data: string;

a.component.html

<div [innerHtml]="data"></div>

答案 1 :(得分:0)

ng-template是用于有条件地显示“复杂内容”的适当工具。

我将不再提供冗长的答案,而只是提供指向Angular大学博客文章的链接:https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/ 因为我在移动。

它比较ng-template ng-container和更多。

处理这些主题的博客比提到的博客多。这是谷歌搜索ng-template的第一个结果。