【问题标题】:How can I make two HTML templates conditionally for one component with Angular 8如何使用 Angular 8 有条件地为一个组件制作两个 HTML 模板
【发布时间】:2021-12-11 01:13:09
【问题描述】:

我有这个组件:

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css'],
  providers: [YoutubeService]
})

由于某些原因,我需要有条件地创建另一个 templateURL form1.component.html

这个组件包含一个带有两个按钮的对话框( button1button2 ) 如果我点击 button1 我想要 form.component 加载 form.component.html 如果我点击 button2 我想要 form.component 加载 form1.component.html

如何有条件地为一个组件使用 2 个 HTML 文件?

有这样的解决方案吗?

@Component({
  selector: 'app-form',
  templateUrl: if (condition) => './form.component.html' else './form1.component.html',
  styleUrls: ['./form.component.css'],
  providers: [YoutubeService]
})

【问题讨论】:

    标签: angular typescript components angular8 angular-ng-if


    【解决方案1】:

    角度组件不是这样工作的。

    您需要在组件的 HTML 中使用 *ngIf 条件,或者您需要有条件地将子组件插入到组件的模板中。

    如果你想在这些子组件之间共享逻辑,它们可以扩展一个基类:

    abstract class ComponentBase { }
    class ChildComponentOne extends ComponentBase { }
    class ChildComponentTwo extends ComponentBase { }
    

    【讨论】:

      【解决方案2】:

      应用组件.html:

      <first-component *ngIf="compoService.isfirst"></first-component>
      <second-component *ngIf="!compoService.isfirst"></second-component>
      

      应用组件.ts:

      import { CompoService } from '../compo.service';
      //... other imports
      
      //... logic
      
      constructor(public compoService: CompoService) {}
      
      //... logic
      

      compo.service.ts:

      export class CompoService {
      
        ServiceSubject = new Subject<any[]>();
      
        isfirst: boolean = true;
      
        constructor() { }
      
        template1() {
          this.isfirst = false;
        }
      
        template2() {
          this.isfirst = true;
        }
      

      对话框组件.html:

      <input type="radio" name="radio3" id="template1">     
       <label for="template1" (click)="template1()">load templae 1</label>
      
      <input type="radio" name="radio3" id="template2">           
       <label for="template2" (click)="template2()">load templae 2</label>
      

      对话框组件.ts:

      import { CompoService } from '../compo.service';
      //... other imports
      
      //... logic
      
      constructor(public compoService: CompoService) {}
      
        template1() {
          this.compoService.template1();
        }
      
        template2() {
          this.compoService.template2();
        }
      

      【讨论】:

        猜你喜欢
        • 2021-12-11
        • 2021-09-30
        • 2019-12-27
        • 2021-11-08
        • 1970-01-01
        • 2016-04-16
        • 2020-01-02
        • 2018-02-07
        • 1970-01-01
        相关资源
        最近更新 更多