学习angular已经两周了,简单的基本知识已经掌握,在学习的过程中遇到很多问题,和大家分享一下~
1. [(ngModel)]数据双向绑定,即数据在DOM和组件之间是双向传递的,为了实现低耦合实现数据的封装,通常会引入自定义对象(这些对象往往是为了接受处理后端传来的数据),在DOM中通过 对象.属性名 的方式得到值
-
export class Student{
-
public name: string; // 姓名
-
public sex: string; // 性别
-
constructor(){}
-
}
-
export class StudentComponent implements OnInit {
-
student: Student;
-
constructor(public fb: FormBuilder){}
-
ngOnInit(){}
-
}
-
<input pInputText [(ngModel)]="student.name">{{student.name}}
-
<input pInputText [(ngModel)]="student.sex">{{student.sex}}
运行之后发现报错,反正就是找不到name和sex这两个属性...
原因:只是定义了Student这个对象,但是没有创建,需要new一下
2.Form表单相关问题
百度了好多也没有找到自己满意的答案,作为刚入门者,需要一个简单而清晰的案例
-
<form [formGroup]="addData" (ngSubmit)="onSubmit(addData)" *ngIf="product">
-
<div class="ui-grid ui-grid-responsive ui-fluid">
-
<div class="ui-grid-row">
-
<div class="ui-g-3 control-label">
-
<label>姓名:</label>
-
</div>
-
<div class="ui-g-5">
-
<input pInputText formControlName="name" class="label-height"
-
[(ngModel)]="student.name" placeholder="请输入姓名">
-
</div>
-
<div class="ui-g-4">
-
<span style="color: red">*</span>
-
<div style="color: red" class="label-height" class="ui-message ui-message-
-
error ui-corner-all" *ngIf="!addData.controls['name'].valid &&
-
addData.controls['name'].dirty">
-
<i class="fa fa-close"></i>请输入姓名
-
</div>
-
</div>
-
</div>
-
</div>
-
</form>
-
validForm(){
-
this.addData = this.fb.group({
-
'name' = new FormControl('', Validators.required);
-
});
-
}
忽略代码中的页面布局,formControlName会对应由FormGroup创建的表单的相同字段,如果addData中没有找到和formControlName相同的名称,会报找不到name为该名称的control
3.路由配置
在根模块下创建一个路由配置文件 app-routing.module.ts
ng g model app-routing --flat --module=app
--flat:把这个文件放进src/app中,而不是单独的目录中
--module=app告诉CLI把它注册到AppModule中的import数组中
-
import { NgModule } from '@angular/core';
-
import { Routes, RouterModule } from '@angular/rout;
-
import { DemoComponent } from './components/student/student.component';
-
const routes: Routes = [
-
{path: '', redirectTo: '/studentInfo', pathMatch: 'full'},
-
{path: 'studentInfo', component: ProductComponent},
-
{path: 'productInfo/:name', component: ProductComponent}
-
];
-
@NgModule({
-
imports: [ RouterModule.forRoot(routes)],
-
exports: [ RouterModule ]
-
})
-
export class AppRoutingModule { }
添加路由定义,通过不同的URL访问不同的页面
一般有两个属性,path用来匹配URL字符串,component表示当导航到此路由时,创建哪个组件。
通过加入import中初始化路由 imports: [ RouterModule.forRoot(routes) ]
修改app.component.html,改为<router-outlet></router-outlet>指定在哪里显示路由到的视图。
添加默认路由
{ path: '', redirectTo: '/xxxx', pathMatch: 'full' }
会自动定向到/xxxx,并自动加载组件