Angular2_学习笔记

创建项目
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'; // 引入input

export class HomeComponent implements OnInit {
  @Input() bindValue;   // 用input修饰传入的数据
}

<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();
}

路由配置
// app.routers.ts

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);

// app.model.ts
import { router } from './app.routers'
@NgModule({
  imports: [
    router
  ]
})
export class AppModule { }

// app.component.html
<a [routerLink]="['/']">home</a>
<router-outlet></router-outlet>

路由参数
// app.routers.ts 定义
const appRouters:Routers = [
    {
        path: 'directory/:params',  // 定义参数
        component: DirectoryComponent
    }
];

// app.component.html 使用
<a [routerLink]="['/directory', params]">directory</a>

// app.component.js 赋值
export class AppComponent {
  params = 'params'
}

// directory.component.ts 接收
import { ActivatedRoute } from '../../../node_modules/@angular/router';

export class DirectoryComponent implements OnInit {
  title:string;
  constructor(private route:ActivatedRoute) {
    this.params = route.snapshot.params['params']
  }
}

猜你喜欢

转载自blog.csdn.net/nick_yangxiaotong/article/details/81058403
今日推荐