0

I have a component belonging to a custom library:

<my-icon>

In order to have the icon, I should set the property [name] of this component. Something like this:

<my-icon [name]='warning'></my-icon>

I am dinamically creating these icons with TypeScript:

if (myCondition) {
    let icon = <HTMLElement>document.createElement('my-icon');
}

How should I set the property [name] in my variable icon in order to have the same result than above? I've tried icon.setAttribute('name','warning') but it doesn't work (that sets the HTML attribute name, and not the input name of the underlying Angular component.

1
  • 1
    you should use Renderer2 to manipulate DOM. It has also methods to setProperty, setAttribute etc Commented May 4, 2018 at 13:21

1 Answer 1

1

document.create does not create Angular component but only DOM element. If you want to dynamically create Angular component you should inject ComponentFactoryResolver service

constructor(private componentResolver: ComponentFactoryResolver) { }

which can be later used like this:

// create factory for icon component
const factory = this.componentResolver.resolveComponentFactory(MyIconComponent);

// create icon component and append it next to anchor element
const icon = this.anchor.createComponent(factory);

// assign some value to component input
icon.instance.name = 'icon name';

Anchor element can be obtained using ViewChild e.g. if your component template looks like this:

`<div #iconsHere></div>`

you'll have to add the following annotation:

  @ViewChild('iconsHere', {read: ViewContainerRef}) anchor: ViewContainerRef;

Please note that dynamically created components have to be declared as entry components in your module.

@NgModule({
  ...
  entryComponents: [ MyIconComponent ]
})
export class AppModule { }

Demo: https://stackblitz.com/edit/angular-jukjib

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

Comments

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.