Reputation: 27738
My final goal is to build a component to wrap Google Map. A google map object has lots of options.
In Angular1, I read attributes to build a map object options.
With Angular2, I want to do it differently to use properties binding using inputs
, so that I can achieve one way or two-way binding.
As a first step, with this plunker, https://plnkr.co/edit/PXg79x?p=preview, I tried to read many properties from html and I have set inputs for multiple options. e.g., a, b, c, d, e, f
@Component({
selector: 'my-app',
providers: [],
inputs: ['a', 'b', 'c', 'd', 'e', 'f'],
template: `
<div>
<h2>Hello {{name}}</h2>
inputs: {{inputs | json}} <br/>
a:{{a}}, b:{{b}}, c:{{c}}, d:{{d}}, e:{{e}}, f:{{f}}
</div>
`,
directives: []
})
export class App {
constructor() {
this.name = 'Angular2 (Release Candidate!)';
}
}
and I used in html like this.
<my-app [a]="1" [b]="2" [c]="3" [d]="4" [e]="5" [f]="6">
loading...
</my-app>
I was expecting that I see a:1, b:2, c:3, d:4..
and so on.
But instead, I see a:, b:, c:, d:, e:..
What am I doing wrong here?
---- EDIT ----
Also, I don't expect the answer, but if someone can tell me that I can define these inputs dynamically with or without defining inputs
or @Input
, it would be very appreciated.
Upvotes: 0
Views: 1110
Reputation: 1037
This may sound dumb, but you cant do this with the root component (my-app).. you need to do this in a child component. Since my-app
is the entire angular application.
e.g.
src/my-component.ts
file
import {Component, Input} from '@angular/core'
@Component({
selector: 'my-component',
providers: [],
inputs: ['a', 'b', 'c', 'd', 'e', 'f'],
template: `
<div>
<h2>Hello {{name}}</h2>
inputs: {{inputs | json}} <br/>
a:{{a}} b:{{b}} c:{{c}} d:{{d}} e:{{e}} f:{{f}}
</div>
`,
directives: []
})
export class MyComponent {
constructor() {
this.name = 'Angular2 (Release Candidate!)';
}
}
src/app.ts
file
//our root app component
import {Component, Input} from '@angular/core'
import { MyComponent } from './my-component';
@Component({
selector: 'my-app',
template: `
<my-component a="1" b="2" c="3" d="4" e="5" f="5">
</my-component>
`,
directives: [ MyComponent ]
})
export class App {
}
Also, [a]="1"
tries to look for a variable called 1
in the class context and evaluate it to get its value.. while a="1"
gets the value "1"
as a string.
So, having [a]="myVariable"
would get whatever value is in myVariable
, while a="myVariable"
will pass a string literal with the value "myVariable"
Plunker: https://plnkr.co/edit/DhHgED?p=preview
Makes sense?
Edit:
To my knowledge, you cant define inputs dynamically since angular2 compiler needs to know before hand the component definition.
Upvotes: 1