角度将组件动态添加到另一个组件

时间:2020-05-03 14:39:20

标签: javascript angular typescript rxjs

这对我来说是FrontEnd框架应具有的超级基本功能。
但是我无法在Angular中找到它。

我有这种情况:
一个组件通过异步调用(在此示例中为假调用)向外部服务发出一些请求,然后根据响应(如果数字为奇数或偶数)将该组件添加到该视图中一个或另一个组件。 >

考虑这个小例子

import { NavigationEvents } from '@react-navigation/native';

<NavigationEvents
   onDidFocus={() => Alert.alert('Home')}
   onDidFocus={console.log('Home Screen')
/> 

完整的代码示例在此处https://stackblitz.com/edit/angular-7dtg8w

我想动态添加 import { Component, OnInit } from '@angular/core'; import { of, merge, Observable } from 'rxjs'; import { mapTo, delay } from 'rxjs/operators'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent implements OnInit { constructor() { } ngOnInit() { const subscribe = this.serverFakeCall().subscribe( val => { console.log("received value ", val); if (val%2 == 0) { // The OddComponent should be displayed } else { // The EvenComponent should be displayed } }); } private serverFakeCall() : Observable<number>{ const randomNumber = Math.floor((Math.random() * 2)) return of(randomNumber).pipe(delay(3000)) } } OddComponent 我不想将它们都添加到模板中,然后使用“ EvenComponent

“隐藏”一个或另一个

达到此结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

在Angular v9之前这是不可能的。

现在,由于有了Ivy(View Engine的后继者),引入了 locality 的概念,并且可以延迟加载组件,即可以 load 在运行时动态地修改组件。

great article from Natanel Basal解释了如何实现这一点。 文章中的一个摘要:

import { FooComponent } from './foo/foo.component';

@Component({
  template: `
    <button (click)="loadFoo()">Load FooComponent</button>
    <ng-container *ngIf="foo">
       <ng-template [ngComponentOutlet]="foo | async"></ng-template>
    </ng-container>
  `
})
export class AppComponent {
  foo: Promise<Type<FooComponent>>;

  loadFoo() {
    if (!this.foo) {
      this.foo = import(`./foo/foo.component`)
                       .then(({ FooComponent }) => FooComponent);
    }
  }
}

我建议您阅读整篇文章以获得有关它的所有详细信息。