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()"/>


     
  • 相关阅读:
    WPF 本地化语言设置
    WPF 调节树状图滚动条值
    WPF中ListBox的使用注意事项
    SQL 树状结构表中查出所所有父级/子级
    Vue创建
    wpf 控件注意事项
    链表习题(1)-设计一个递归算法,删除不带头结点的单链表L中所有值为x的结点
    排序-快速排序
    排序-堆排序
    图-图的遍历
  • 原文地址:https://www.cnblogs.com/htuthf/p/8018522.html
Copyright © 2011-2022 走看看