zoukankan      html  css  js  c++  java
  • 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()"/>


     
  • 相关阅读:
    使用snmp+mrtg监控CPU、流量、磁盘空间、内存
    ISO20000
    nginx入门篇----nginx服务器基础配置
    oracle数据库备份和还原
    oracle创建删除用户和表空间
    Centos 6.5安装oracle 11g
    nginx入门篇----安装、部署、升级
    vue 高德地图 地图初始化显示接口返回的多个经纬度
    vue element UI el-table 单元格中超出字省略号显示
    vue + element ui 打印
  • 原文地址:https://www.cnblogs.com/htuthf/p/8018522.html
Copyright © 2011-2022 走看看