⚠️ This lesson is retired and might contain outdated information.

Set Properties on Dynamically Created Angular 2 Components

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

When you generate Angular 2 components, you’re still able to access the component instance to set properties and invoke methods from the component class.

[00:00] With each of these widgets that we have created, they are all Widget 3s. Right now, they're blank in here. Let's set a default value for that input.

[00:09] We'll do that by creating an input. This is component input, don't confuse it with an HTML input, meaning that we can pass in a message. Typically, in a template, you would have my-component, and then pass in something through message like this and a string of some message.

[00:31] But since we're going to create these programmatically, and I'll start with a default value of, say, default value. When I set value to the message, each of these will have default value in the input.

[00:53] I want to be able to change that programmatically from the component that creates it. In the home component, I could actually get a reference to this widget that's created. I'll say widgetref. Let's format this a little bit, so you can read it. Then on the widgetref, you can get an instance of the component that that reference is referencing.

[01:18] On that instance, you can set things like the message. I'll say, "I'm last." From this reference that we're getting by creating the component, you just say widgetref.instance and, on that instance, then you can start setting the properties, the inputs, or anything that's on that component just as if you're accessing an instance of this class here. Then those values we passed in to the template as they would normally as the message is here.