angular-cn/public/docs/js/latest/guide/making-components.jade

88 lines
2.5 KiB
Plaintext

.l-main-section
h2#section-its-all-a-tree It's all a tree
p.
As mentioned earlier, you build Angular applications as a tree of nested components. You've seen how to create
a top-level component. You add child components to a parent component by using them in the parent component's
template.
p.
Given a bootstrapping template with a <code>&lt;parent&gt;</code> tag in the body, you can create a parent
component that uses a <code>&lt;child&gt;</code> component like so:
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//TypeScript
@Component({
selector: 'parent'
})
@View({
template: `
&lt;h1&gt;{{ message }}&lt;/h1&gt;
&lt;child&gt;&lt;/child&gt;
`,
directives: [ChildComponent]
})
class ParentComponent {
message: string;
constructor() {
this.message = "I'm the parent";
}
}
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
function ParentComponent() {
this.message = "I'm the parent";
}
ParentComponent.annotations = [
new angular.ComponentAnnotation({
selector: "parent"
}),
new angular.ViewAnnotation({
template:
'&lt;h1&gt;{{ message }}&lt;/h1&gt;' +
'&lt;child&gt;&lt;/child&gt;',
directives: [ChildComponent]
})
];
p You then just need to write the <code>ChildComponent</code> class to make it work:
code-tabs
code-pane(language="javascript" name="TypeScript" format="linenums").
//TypeScript
@Component({
selector: 'child'
})
@View({
template: `
&lt;p&gt; {{ message }} &lt;/p&gt;
`
})
class ChildComponent {
message: string;
constructor() {
this.message = "I'm the child";
}
}
code-pane(language="javascript" name="ES5" format="linenums").
//ES5
function ChildComponent() {
this.message = "I'm the child";
}
ChildComponent.annotations = [
new angular.ComponentAnnotation({
selector: "child"
}),
new angular.ViewAnnotation({
template: '&lt;p&gt; {{ message }} &lt;/p&gt;'
})
];
p.
Notice that in addition to using the <code>&lt;child&gt;</code> element in the parent template, you also need to
add <code>ChildComponent</code> in <code>ParentComponent</code>'s list of directives.