Search code examples
angulartypescriptcomponentsangular8angular-ng-if

How can I make two HTML templates conditionally for one component with Angular 8


I have this component:

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

For some reasons I need to create an other templateURL form1.component.html conditionally.

this component contains a dialog with two buttons ( button1 and button2 ) if i click button1 i want form.component load form.component.html and if i click button2 i want form.component load form1.component.html

How can I conditionally use 2 HTML files for one component?

is there a solution like this?

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

Solution

  • app-component.html :

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

    app-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;
      }
    

    dialog-component.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>
    

    dialog-component.ts :

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