Angularv4.初体验


907 浏览 3 years, 10 months

20 传递数据到组件 Passing Data to Components

版权声明: 转载请注明出处 http://www.codingsoho.com/

src/app/search/search.component.ts

import { Component, OnInit, Input} from '@angular/core';

export class SearchComponent implements OnInit {
    searchLocation = "Newport Beach"
    searchQuery: string;
    @Input()
    passedQuery: string;     
    ngOnInit() {
    // console.log(this.passedQuery)
    if (this.passedQuery){
        this.searchQuery = this.passedQuery
    }
 submitSearch(event, formData){
      let searchedQuery = formData.value['q']
      if (searchedQuery){
         this.router.navigate(['/search', {q: searchedQuery}])
      }
  }

search-detail.component.html

<search class="text-center search-inline" [passedQuery]='query'></search>

这儿的passedQuery是传递进来的query,在selector里设置了<search [passedQuery]='query'></search>
passedQuery用方括号包起来了,表示后面的query是变量,否则将会作为字符串处理

Input是一个装饰器,帮助你向component传递数据。这个地方passedQuery用于初始化设置
<search [passedQuery]='query'></search> + @Input() passedQuery: string; >> 放在selector里面干嘛用?

如果在模板文件里,<search class="text-center search-inline" [passedQuery]='query'></search>,那么ngOnInit里的console.log(this.passedQuery)可以打印出它的初始值

Search detail的搜索框里已出现了,但是导航条上的还没有,同样的方法,我们来修改app component

src/app/app.component.html

    // <search></search> 
    <search [passedQuery]='query'></search>

src/app/app.component.ts

import { Component, OnInit, OnDestroy} from '@angular/core';
import { ActivatedRoute } from '@angular/router';

// export class AppComponent {
export class AppComponent implements OnInit{
  title = 'My Apps';
  description = 'A new app';
  query: string;
  private routeSub:any;


  constructor(private route:ActivatedRoute){
      this.routeSub = route.params.subscribe(params=>{
          console.log(params)
          this.query = params['q']
      })
  }

  ngOnInit() {

  }
  ngOnDestroy(){
      this.routeSub.unsubscribe()
  }
}

在导航条执行搜索,显示结果如下

有一个问题是导航条的搜索框和component里的搜索框内容不能做到一致,暂时没找到解决方案,视频教程也没有,先不处理,将component的搜索框先去掉。