Angular --主从组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aimin_com/article/details/88557604

前言

什么是主从组件,就是将组件分为主组件和从组件,目的就是让我们更加好维护并且便于利用,将大化小,就如同我们之前的模板类一样,我们以上次做的英雄榜作为例子来进行切割使用。




开始制作

  1. 我们首先新建一个新组件:hero-detail
	ng generate component hero-detail
  1. 编写模板:我们将之前heroes模板(html)中的下面的代码剪切到我们新建立的这个组件的模板中来:
	<div *ngIf="hero">
	
	  <h2>{{hero.name | uppercase}} Details</h2>
	  <div><span>id: </span>{{hero.id}}</div>
	  <div>
	    <label>name:
	      <input [(ngModel)]="hero.name" placeholder="name">
	    </label>
	  </div>
	
	</div>

  1. 在我们新建组件中ts文件中绑定hero属性,并且我们需要在本来的import { Component, OnInit} from ‘@angular/core’; 中添加Input属性,以及在export中添加@Input属性
	import { Component, OnInit, Input } from '@angular/core';
	import { Hero } from '../hero';
	
	@Component({
	  selector: 'app-hero-detail',
	  templateUrl: './hero-detail.component.html',
	  styleUrls: ['./hero-detail.component.css']
	})
	export class HeroDetailComponent implements OnInit {
	
	
	  @Input() hero:Hero;
	
	  constructor() { }
	
	  ngOnInit() {
	  }
	
	}

  1. 我们再回到heroes的html中,将我们做的新的组件添加到heroes组件中,用来显示。
	//我们在此页面中最下面添加:
	
	<app-hero-detail [hero]="selectedHero"></app-hero-detail>
	
	//注意: [hero]="selectedHero" 是Angular的属性绑定语法,
	//这是一个单向绑定



小结

此次结果和我们之前的英雄榜是一样的,这个也是为了松耦合,将我们共同用到的代码抽离出来便于维护和复用,这样子我们未来的代码会经常光顾这个组件了,以后我们哪里需要就可以这串代码将以修改写入即可了(<app-hero-detail [hero]=“selectedHero”>

猜你喜欢

转载自blog.csdn.net/aimin_com/article/details/88557604