Er Vipin Sharma
Er Vipin Sharma

Reputation: 2639

How to pass binding(two way data binding) from HTML file to Typescript file in Angular 2

let me simplify the specific issue:

html looks like:

<div [innerHtml]="htmlToAdd"></div>

i have an array

 TrueFalseOptions = [
        {key: 'true' , value: 'true'},
        {key: 'false' , value: 'false'}
    ];

i am setting the innerhtml of a div as follows in my ts file:

this.htmltoAdd = "<label>Required</label><select class='form-control'> <option *ngFor='let c of {{TrueFalseOptions}}' [ngValue]='{{c.value}}'>c.key</option></select>";

if i don't use the pipe - i do not see anything from the above statement. If i use a pipe as described below:

@Pipe({name: 'safeHtml'})
export class Safe {
    constructor(private sanitizer:DomSanitizer){}

    transform(style) {
         return this.sanitizer.bypassSecurityTrustHtml(style);
    }
}

then i can see the select drop down but the binding is missing still.

What could be the issue in this?

Upvotes: 0

Views: 1035

Answers (1)

Denko Mancheski
Denko Mancheski

Reputation: 2719

There are some core things wrong with this approach:

  1. You cannot use innerHTML and expect that the bindings will work (which simply means that the angular syntax wont work. (no components, directives will be initialized)
  2. You should not ever touch the DOM directly like you do in that component (you should try and forget document.getElementById and similar functions which are directly manipulating the DOM

To answer your question: What you actually need to do, is to put that html that is in the class into the template, and wrap it in a <div *ngIf="ele.Required"/>. Whenever that Required attribute is true, this div will be shown.

P.S. If you ever use innerHTML to add static content between, you can bind it directly like: <div [innerHTML]="theStringVariable"></div>

Upvotes: 0

Related Questions