A-A+
angular2通俗化入门教程(2)component(组件)
上一节,我们学会了怎么安装anglarjs2,过程有点曲折,但总的来讲,她跑起来了,而且看见了那红红的图标。
这一节,我们主要来了解组件,
组件是什么呢?
1.新建一个组件:
执行这个命令 ng g c hello
一个叫hello的组件就建好了。
PS C:\angularjs\my-app> ng g c hello installing component create src\app\hello\hello.component.css create src\app\hello\hello.component.html create src\app\hello\hello.component.spec.ts create src\app\hello\hello.component.ts update src\app\app.module.ts PS C:\angularjs\my-app>
2.修改一下,增加点内容
修改hello.component.ts
加入这么一句
msg="hello world!"
最后文件变成这样的。
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-hello', templateUrl: './hello.component.html', styleUrls: ['./hello.component.css'] }) export class HelloComponent implements OnInit { msg="hello world!" constructor() { } ngOnInit() { } }
修改一下
hello.component.html
<p> {{msg}} </p>
3.引用这个组件
首先要知道,我们这个组件的selector名字
selector: 'app-hello',
然后,要注意,在我们执行新建命令时,程序已自动给我们创建的新的组件加到了app.module.ts
所以,我们就可以在app.component.html 中通过选择器来引用它了。
<div style="text-align:center"> <h1> Welcome to {{title}}! </h1> <app-hello></app-hello> </div>
这就是最后的效果,可以看到。我们做的第一个组件,已成功运行了。
打赏作者
如果文章对您有所帮助请打赏支持本站发展。