angular入门总结

学习angular已经两周了,简单的基本知识已经掌握,在学习的过程中遇到很多问题,和大家分享一下~

1. [(ngModel)]数据双向绑定,即数据在DOM和组件之间是双向传递的,为了实现低耦合实现数据的封装,通常会引入自定义对象(这些对象往往是为了接受处理后端传来的数据),在DOM中通过 对象.属性名 的方式得到值

 
  1. export class Student{

  2. public name: string; // 姓名

  3. public sex: string; // 性别

  4. constructor(){}

  5. }

  6. export class StudentComponent implements OnInit {

  7. student: Student;

  8. constructor(public fb: FormBuilder){}

  9. ngOnInit(){}

  10. }

 
  1. <input pInputText [(ngModel)]="student.name">{{student.name}}

  2. <input pInputText [(ngModel)]="student.sex">{{student.sex}}

运行之后发现报错,反正就是找不到name和sex这两个属性...

原因:只是定义了Student这个对象,但是没有创建,需要new一下

2.Form表单相关问题

百度了好多也没有找到自己满意的答案,作为刚入门者,需要一个简单而清晰的案例

 
  1. <form [formGroup]="addData" (ngSubmit)="onSubmit(addData)" *ngIf="product">

  2. <div class="ui-grid ui-grid-responsive ui-fluid">

  3. <div class="ui-grid-row">

  4. <div class="ui-g-3 control-label">

  5. <label>姓名:</label>

  6. </div>

  7. <div class="ui-g-5">

  8. <input pInputText formControlName="name" class="label-height"

  9. [(ngModel)]="student.name" placeholder="请输入姓名">

  10. </div>

  11. <div class="ui-g-4">

  12. <span style="color: red">*</span>

  13. <div style="color: red" class="label-height" class="ui-message ui-message-

  14. error ui-corner-all" *ngIf="!addData.controls['name'].valid &&

  15. addData.controls['name'].dirty">

  16. <i class="fa fa-close"></i>请输入姓名

  17. </div>

  18. </div>

  19. </div>

  20. </div>

  21. </form>

 
  1. validForm(){

  2. this.addData = this.fb.group({

  3. 'name' = new FormControl('', Validators.required);

  4. });

  5. }

忽略代码中的页面布局,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数组中

 
  1. import { NgModule } from '@angular/core';

  2. import { Routes, RouterModule } from '@angular/rout;

  3. import { DemoComponent } from './components/student/student.component';

  4.  
  5. const routes: Routes = [

  6. {path: '', redirectTo: '/studentInfo', pathMatch: 'full'},

  7.  
  8. {path: 'studentInfo', component: ProductComponent},

  9.  
  10. {path: 'productInfo/:name', component: ProductComponent}

  11. ];

  12.  
  13. @NgModule({

  14. imports: [ RouterModule.forRoot(routes)],

  15. exports: [ RouterModule ]

  16. })

  17. 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,并自动加载组件

猜你喜欢

转载自blog.csdn.net/weixin_42400955/article/details/81352793