1

I am trying create an input element from typescript to html in angular 4. But when I try put [(ngModel)] not works. How I do that method ? Someone know how ?

createElement() {
    this.input = document.createElement('input');
    this.input.setAttribute('matInput', '');
    this.input.setAttribute('placeholder', 'Tema');
    this.input.setAttribute('[(ngModel)]', 'module.theme');
    this.input.setAttribute('name', 'theme');

    return (<HTMLDivElement>(document.getElementById('ejemplo').appendChild(this.input)));
  }

1 Answer 1

1

Something like

 this.input.setAttribute('[(ngModel)]', 'module.theme');

is not supposed to work. Property/attribute bindings and component/directive instantiation only happens for markup added to a components template statically.

If it is added dynamically it won't have any effect. If you need this, you can create and compile a component at runtime and add that component dynamically (to a statically defined ViewContainerRef).

Alternatively you can use imperative code to update the DOM.

Sign up to request clarification or add additional context in comments.

4 Comments

And how to do the "create and compile a component" thing?
The link in this answer stackoverflow.com/a/46578036/217408 seems to be recent enough. There are several other related questions/answers on SO.
Thanks, but that creates the component from a html string, not from a HTMLElement object. Would be possible without calling .innerHTML? And how to do it in a directive (having access only to the ElementRef and not ViewContainerRef)?
Sorry, I can't help you with this topic. I never used it myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.