簡體   English   中英

Angular 5父級調用子級組件

[英]Angular 5 Parent calling child component

我有一個使用primefaces / primeng庫的樹組件。 當我單擊樹節點時,我希望孩子(一個帳戶注冊者)為給定節點加載帳戶。 我無法使其正常工作。 該帳戶是通過有角度的服務加載的。

樹組件:

import { Component, OnInit, Injectable, ViewChild } from '@angular/core';
import { Tree } from 'primeng/tree';
import{ TreeModule } from 'primeng/tree';
import { TreeNode } from 'primeng/api';
import { Router } from '@angular/router';
import { AccountRegisterComponent } from '../account-register/account-register.component';


@Component({
  selector: 'app-accounts',
  templateUrl: './accounts.component.html',
  styleUrls: ['./accounts.component.css']
})
@Injectable()
export class AccountsComponent implements OnInit {

@ViewChild(AccountRegisterComponent)
private accountRegister: AccountRegisterComponent;

  constructor(private router: Router) { }


  public nodes : TreeNode[];
  ngOnInit() {
    this.nodes =  [
      {     
          label: "Assets",
          data: "1",
          expandedIcon: "fa-folder-open",
          collapsedIcon: "fa-folder",
          selectable:true,
          children: [ 
            {
            label: "Asset1",
            data: "2",
            expandedIcon: "fa-folder-open",
            collapsedIcon: "fa-folder",
            selectable:true
          } 
        ]
      },
      {
        label: "Liabilities",
        data: "3",
        expandedIcon: "fa-folder-open",
        collapsedIcon: "fa-folder",
        selectable:true
    },
    {
      label: "Income",
      data: "4",
      expandedIcon: "fa-folder-open",
      collapsedIcon: "fa-folder",
      selectable:true
  },
  {
    label: "Expenses",
    data: "5",
    expandedIcon: "fa-folder-open",
    collapsedIcon: "fa-folder",
    selectable:true
},
    ];

  }

  nodeUnselect(event) {
    console.log("unselect " + event.node.label);
}

  nodeSelect(event) {
     this.router.navigateByUrl('/account/' + event.node.data);
     this.accountRegister.id = event.node.data;     
     console.log(event.node.label);
}
  expandAll(){
    this.nodes.forEach( node => {
        this.expandRecursive(node, true);
    } );
}

collapseAll(){
    this.nodes.forEach( node => {
        this.expandRecursive(node, false);
    } );
}

private expandRecursive(node:TreeNode, isExpand:boolean){
    node.expanded = isExpand;
    if(node.children){
        node.children.forEach( childNode => {
            this.expandRecursive(childNode, isExpand);
        } );
    }
  }
}

注冊組件,該組件調用服務以獲取給定父請求的給定帳戶ID的數據:

import { Component, OnInit, Input, OnChanges, DoCheck } from '@angular/core';
import { NgSwitchCase } from '@angular/common';
import { ActivatedRoute} from '@angular/router';
import { Table } from 'primeng/table';
import { GuidGenService } from '../services/guid-gen.service';
import { SelectItem } from 'primeng/api';
import { Dropdown } from 'primeng/dropdown';
import { AccountsService } from '../services/accounts.service';

@Component({
  selector: 'app-account-register',
  templateUrl: './account-register.component.html',
  styleUrls: ['./account-register.component.css']
})
export class AccountRegisterComponent implements OnInit, OnChanges, DoCheck {

  @Input()
  public id : number;


  accounts : any[];

  cols: any[];

    dates: SelectItem[];

    colors: SelectItem[];

    selectedAccount: SelectItem[];
    targetAccounts: SelectItem[];

  constructor(private route: ActivatedRoute, private guidGen : GuidGenService, private accountServ : AccountsService) {
    this.route.params.subscribe( params => this.id = params.id );

    this.accounts =  accountServ.getAccounts(this.id);
    console.log("accounts is " + this.accounts.length)
  }

  public SetAccounts(id: number)
  {
    this.id=id;
    this.accounts = this.accountServ.getAccounts(this.id);
  }
  ngOnChanges()
  {
    console.log("ngOnChanges " + this.id.toString() );

  }

  AddClick()
  {

   var newId = this.guidGen.GetGuid();
    this.accounts.push(  { id: newId, date: 'New G' + newId, description: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' })
  }
  DeleteClick(rowId){

    console.log("Delete " + rowId );
    var data = this.accounts.filter( val => val.id != rowId);
    this.accounts = data;

  }
  ngDoCheck() {

    //Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
    //Add 'implements DoCheck' to the class.
    console.log("ngDoCheck() " + this.id.toString());

  //  this.accounts = this.accountServ.getAccounts(this.id);
  }
  ngOnInit() {
    console.log("ngInit");

    this.targetAccounts = [ 
      { label: "Cash", value:'cash'},
      { label: "Checking", value:'checking'},
      { label: "Investment", value:'investment'},
  ];
    this.cols = [
      { field: 'date', header: 'Date' },
      { field: 'description', header: 'Description' },
      { field: 'target', header: 'Target Account' },
      { field: 'amount', header: 'Amount' },
    ];

    var dt = new Date();
    dt.setUTCDate(Math.random() * 30);

    // if ( this.accounts == undefined )
    // {
    //   this.accounts = this.accountServ.getAccounts(this.id);
    // }
  }

}

服務:

        import { Injectable } from '@angular/core';

@Injectable()
export class AccountsService {

  constructor() { }

  accounts: any[];

  getAccounts(id:number) : any[]
  {


    var dt = new Date();
    this.accounts = [];
    this.accounts = [
      { id:"1", date: dt.toLocaleDateString(), description: 'Home Depot' + id.toString(), target: 'cash', amount: Math.random() * 1000.0},
      { id:"2", date: dt.toLocaleDateString(), description: 'Beer', target: 'checking', amount: Math.random() * 1000.0},
      { id:"3", date: dt.toLocaleDateString(), description: 'Salary', target: 'investment', amount: Math.random() * 1000.0},
      { id:"4", date: dt.toLocaleDateString(), description: 'AFAFA', target: '22%' , amount: Math.random() * 1000.0},
      { id:"5", date: dt.toLocaleDateString(), description: ' AGAG@$#@$@ ', target: '79%', amount: Math.random() * 1000.0},
      { id:"6", date: dt.toLocaleDateString(), description: 'ABCDEF ', target: ' 65%', amount: Math.random() * 1000.0},
      { id:"7", date: dt.toLocaleDateString(), description: 'Test me', target: '12%' , amount: Math.random() * 1000.0},
      { id:"8",  date: dt.toLocaleDateString(), description: '44%', target: '45%', amount: Math.random() * 1000.0}

    ];
    return this.accounts;
  }

}

事實證明,我需要在訂閱處理程序中調用該服務。

import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { NgSwitchCase } from '@angular/common';
import { ActivatedRoute} from '@angular/router';
import { Table } from 'primeng/table';
import { GuidGenService } from '../services/guid-gen.service';
import { SelectItem } from 'primeng/api';
import { Dropdown } from 'primeng/dropdown';
import { AccountsService } from '../services/accounts.service';

@Component({
  selector: 'app-account-register',
  templateUrl: './account-register.component.html',
  styleUrls: ['./account-register.component.css']
})
export class AccountRegisterComponent implements OnInit, OnChanges {

    @Input()
    public accounts : any[];

    @Input()
    id : Number;

    cols: any[];

    selectedAccount: SelectItem[];
    targetAccounts: SelectItem[];

  constructor(private route: ActivatedRoute, private guidGen : GuidGenService, private accountServ : AccountsService) {

    // Need to call service inside of subscription callback.
    this.route.params.subscribe( params => { this.accounts = accountServ.getAccounts(params.id);this.id = params.id; });

    //this.accounts = accountServ.getAccounts( this.id);
    console.log("accounts is " + this.accounts.length)
  }

  ngOnChanges()
  {
    console.log("ngOnChanges");
  }

  AddClick()
  {

    var newId = this.guidGen.GetGuid();
    this.accounts.push(  { id: newId, date: 'New G' + newId, description: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' })
  }
  DeleteClick(rowId){

    console.log("Delete " + rowId );
    var data = this.accounts.filter( val => val.id != rowId);
    this.accounts = data;

  }
  ngDoCheck() {

    //Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.
    //Add 'implements DoCheck' to the class.
    console.log("ngDoCheck()");

   // this.accounts = this.accountServ.getAccounts(this.id);
  }
  ngOnInit() {
    console.log("ngInit");

    this.targetAccounts = [ 
      { label: "Cash", value:'cash'},
      { label: "Checking", value:'checking'},
      { label: "Investment", value:'investment'},
  ];
    this.cols = [
      { field: 'date', header: 'Date' },
      { field: 'description', header: 'Description' },
      { field: 'target', header: 'Target Account' },
      { field: 'amount', header: 'Amount' },
    ];


  }

}

綁定到“帳戶”並會更新樹的標記。

<p-table #dt [value]="accounts" [columns]="cols" selectiomMode="single"  scrollHeight="150px" [paginator]="true" [rows]="10" >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM