Search code examples
angulartypescriptclarity

Can I generate html code as a string then set that string to be the value of a div in typescript using clarity framework (Angular 7)


I am trying to generate a html code as a string for a Clarity-data-grid using TS then set that string to be the value of a div but the clarity framework won't work unless I actually type the HTML code in the HTML file.

this.component.nativeElement.innerHTML=this.html; -> doing this in TS won't work. But it works if I type everything in (#html below), it will display the table.

html: string ='';
//Generating the grid
private genGrid(data: string): void {
    let request: Object;
    if(data !== ''){
      request = JSON.parse(data);
      for(let prop in request){
        if(request.hasOwnProperty(prop))
          this.html+='<clr-dg-column [clrDgField]="\''+prop+'\'">'+prop+'</clr-dg-column>';
      }
      for(let prop in request){
        if(request.hasOwnProperty(prop))
          this.html+='<clr-dg-cell>'+prop+'</clr-dg-cell>';
      }
    }
}
this.genGrid(someString);
this.component.nativeElement.innerHTML=this.html;

this html code will be generated in my file #html

<div class="card-block" style="padding: 0 10px 10px 10px;"><clr-datagrid><clr-dg-column [clrDgField]="'productId'">productId</clr-dg-column><clr-dg-column [clrDgField]="'productCategoryId'">productCategoryId</clr-dg-column><clr-dg-column [clrDgField]="'productName'">productName</clr-dg-column><clr-dg-column [clrDgField]="'countUnit'">countUnit</clr-dg-column><clr-dg-column [clrDgField]="'manufacturer'">manufacturer</clr-dg-column><clr-dg-column [clrDgField]="'country'">country</clr-dg-column><clr-dg-column [clrDgField]="'description'">description</clr-dg-column><clr-dg-column [clrDgField]="'status'">status</clr-dg-column><clr-dg-column [clrDgField]="'createdDate'">createdDate</clr-dg-column><clr-dg-column [clrDgField]="'createdBy'">createdBy</clr-dg-column><clr-dg-column [clrDgField]="'modifiedBy'">modifiedBy</clr-dg-column><clr-dg-column [clrDgField]="'modifiedDate'">modifiedDate</clr-dg-column><clr-dg-cell>productId</clr-dg-cell><clr-dg-cell>productCategoryId</clr-dg-cell><clr-dg-cell>productName</clr-dg-cell><clr-dg-cell>countUnit</clr-dg-cell><clr-dg-cell>manufacturer</clr-dg-cell><clr-dg-cell>country</clr-dg-cell><clr-dg-cell>description</clr-dg-cell><clr-dg-cell>status</clr-dg-cell><clr-dg-cell>createdDate</clr-dg-cell><clr-dg-cell>createdBy</clr-dg-cell><clr-dg-cell>modifiedBy</clr-dg-cell><clr-dg-cell>modifiedDate</clr-dg-cell>

Solution

  • Because this is an Angular library. It works with Angular context, and it needs to be compiled in order to work properly.

    Setting it as innerHTML of an element (which, BTW, is a very bad practice in Angular) makes it "final", i.e. it will not be compiled to JS code.

    If you want to do that, I suggest you take a look at dynamic components or CDK Portals