• angular4 父组件和子组件通过服务来通讯


    父组件和它的子组件共享同一个服务,可以将这服务理解为全局,同时共用,但是这个服务实例的作用域被限制在父组件和其子组件内,这个组件之外的服务无法访问这个服务。

    import { Injectable } from '@angular/core';
    @Injectable()
    export class myService {
      list:string[] = [];
      constructor() { }
      append(str:any){
        this.list.push(str);
      }
    }
    //faher.compnent.ts
    import { Component, OnInit } from '@angular/core'; 
    import {Service} from "service/
    Service.service";
    @Component({
    selector: 'app-father',
    templateUrl: 'father.component.html',
    styleUrls: ['father.component.css'],
    providers:[Service]
    (注入服务)
    })
     export class FatherComponent implements OnInit {
    list:string[] = [];
    constructor(
        private service:Service
    ) { }
    ngOnInit() {
      this.list = this.service.list;
    } }
    //faher.compnent.html

    <app-child></app-child> <ul> <li *ngFor="let item of list">{{item}}</li> </ul>
    //child.compnent.ts
    import { Component, OnInit } from '@angular/core';
    import {Service} from "service/child.service";
    @Component({
    selector: 'app-child',
    templateUrl: 'child.component.html',
    styleUrls: ['child.component.css'] })
    export class ChildComponent implements OnInit {
    inputText:string = "";
    constructor(
    private service:Service
    ) { }
    ngOnInit() { }
       add(){
      this.service.appeend( this.inputText);
       this.inputText = "";
    } }
    //child.compnent.html
    <input type="text" [(ngModel)]="inputText"/> 
    <input type="button" value="add" (click)="add()"/>


     
  • 相关阅读:
    VIM 配色方案,先保存一下
    ncurses库的介绍与安装
    win7 设置双屏壁纸
    3. Vim入门教程
    2. Vim 概念扫盲
    把Debian 设置中文环境
    静态代码块和构造代码块的区别
    jsp详解(3个指令、6个动作、9个内置对象、11个隐式对象)
    JVM虚拟机详解
    Java 的内置对象
  • 原文地址:https://www.cnblogs.com/htuthf/p/8018522.html
Copyright © 2020-2023  润新知