创建项目
ng new xxx
创建model
ng generate component xxx // 需要先cd到正确的文件夹,之后再执行创建命令
属性绑定
HTML:
<span>
{{readSpan}}
</span>
TS:
export class NavbarComponent implements OnInit {
readSpan = 'Hello World!'
constructor() { }
}
模板绑定
<input type="text" [value]="bindValue.title">
双向数据绑定
<input [(ngModel)]="define.title">
解决ngModel
不可用问题_app.model.ts中引入
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
],
父组件
向子组件
传值
export class AppComponent {
bindValue = {
title: '我将要传递给子组件'
}
}
<app-home [bindValue]="bindValue"></app-home>
import { Input } from '@angular/core';
export class HomeComponent implements OnInit {
@Input() bindValue;
}
<input type="text" [value]="bindValue.title">
事件绑定
<span (click)="clickMe(this.readSpan)">
{{readSpan}}
</span>
<br>
<span on-click="clickMe(this.readSpan)">
{{readSpan}}
</span>
事件传递
<app-home (onList)="list()"></app-home>
export class AppComponent {
list () {
alert('我是父组件的事件')
}
}
<p (click)="clickMe()">
home works!
</p>
import { Output, EventEmitter } from '@angular/core';
@Output() onList = new EventEmitter();
clickMe (val) {
this.onList.emit();
}
路由配置
import { Routes, RouterModule } from "@angular/router";
import { ModuleWithProviders } from "../../node_modules/@angular/compiler/src/core";
import { HomeComponent } from "./home/home.component";
import { DirectoryComponent } from "./directory/directory.component";
const appRouters:Routers = [
{
path: '',
component: HomeComponent
},
{
path: 'directory',
component: DirectoryComponent
}
];
export const router: ModuleWithProviders = RouterModule.forRoot(appRouters);
import { router } from './app.routers'
@NgModule({
imports: [
router
]
})
export class AppModule { }
<a [routerLink]="['/']">home</a>
<router-outlet></router-outlet>
路由参数
const appRouters:Routers = [
{
path: 'directory/:params',
component: DirectoryComponent
}
];
<a [routerLink]="['/directory', params]">directory</a>
export class AppComponent {
params = 'params'
}
import { ActivatedRoute } from '../../../node_modules/@angular/router';
export class DirectoryComponent implements OnInit {
title:string;
constructor(private route:ActivatedRoute) {
this.params = route.snapshot.params['params']
}
}