Home > OS >  Common HTML template for multiple components with added individual code from component
Common HTML template for multiple components with added individual code from component

Time:05-22

In an app there are some differ components, which refer to a common template by using the same url:

@Component({
  selector: 'JG-Percentage',
  templateUrl: '../../../../htmlStructure/htmlBaseTemplate/TemplateVarlist.component.svg',
  styleUrls: ['./Percentage.component.sass']
})

So far so good, also by using angular two-way binding: [(ngModel)]='variable.varLabel'.

But now on some components needs some additional small html code, also with angular two-way binding: [(ngModel)]='variable.inputStr'.

How to inject this added html code into the common template? Or may two html files can be related together to one component?

Thanks for help.

The example is shown on https://angulartool.de

CodePudding user response:

How to inject this added html code into the common template? ...

You can add *ngIf="isCustom" on the additional HTML and use [(ngModel)] inside as you wish. Then in all the Typescript component classes using this same HTML template file, you can have the boolean property for isCustom (or whatever variable name). isCustom will be true for the component classes that use the additional HTML and false for those that do not.

If you are using [(ngModel)] directly on the additional HTML and in case Angular complains that you can't use ngModel together with *ngIf (as is the case with *ngFor), you can wrap this additional HTML in an ng-container and add *ngIf there instead.

<ng-container *ngIf="isCustom">
  <div [(ngModel)]="variable.inputStr">additional HTML</div>
</ng-container>

... Or may two html files can be related together to one component?

A Typescript component class can have only one HTML file. Two HTML files can't be linked to the same typescript component class. (Though it is not the case with styles. One component class can have multiple style files).

  • Related