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

Time:10-26

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]
})

CodePudding user response:

That's not how angular components work.

You'll need to either use an *ngIf condition in your component's HTML, or you need to conditionally insert a sub-component into your component's template.

If you want to share logic between these sub-components, they can extend a base class:

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