如何访问Angular中使用两次或更多次的特定子组件中的方法?

时间:2018-02-11 11:48:58

标签: angular

以下是我正在构建的内容:

一个开关小部件,它是一个复选框和一个按钮。选中该复选框后,该按钮可单击。取消选中该复选框后,该按钮将被禁用。复选框本身可以设置为禁用。

到目前为止我已经建立了什么:

switch.ts,其中包含一个具有3个属性的开关类:name,disabled和state。

export class Switch {
    state: boolean;
    disabled: boolean;
    name: string;
    constructor(name?: string,
                state?: false,
                disabled?: false) {}
}

switch.Component.ts

import { Component, OnInit } from '@angular/core';
import { Switch } from './switch';

@Component({
    selector: 'st-switch',
    templateUrl: './switch.component.html',
    styleUrls: ['./switch.component.scss']
})
export class SwitchComponent {
    switch = new Switch();

    constructor() { }

    ngOnInit() {
        this.switch.name = 'switch name';
        this.switch.state = false;
        this.switch.disabled = false;
    }

  toggle() {
    if(this.switch.state === false) {
      this.switch.state = true;
    } else {
      this.switch.state = false;
    }
  }

  setOn() {
    this.switch.state = true;
  }

  setOff() {
    this.switch.state = false;
  }

  setDisabled() {
    this.switch.disabled = true;
  }

  setEnabled() {
    this.switch.disabled = false;
  }
}

switch.component.html

<label class="switch">
    <input type="checkbox" (click)="toggle()" [disabled]="switch.disabled">
    <span class="slider"></span>
    <button class="btn btn-success btn-confirm" [disabled]="!switch.state">{{switch.name}}</button>
</label>

我遇到的问题

我需要能够设置开关状态,如果它被禁用,并且从另一个使用开关的组件(以编程方式)命名,而另一个组件可以有多个开关。

我尝试了什么

https://www.concretepage.com/angular-2/angular-2-viewchild-example

这是使用switch.component的其他组件(events-form):

import {Component, OnInit, HostListener, ViewChild} from '@angular/core';
import {EventPlannerService} from '../../services/event-planner.service';
import {StEvent} from '../../model/st-event';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {EventsService} from 'app/services/events.service';
import {Notification} from '../notifications/notification';
import {NotificationType} from '../notifications/notification-type';
import {NotificationsService} from '../../services/notifications.service';
import {AbstractControl, FormBuilder, FormGroup, ValidatorFn, Validators} from '@angular/forms';
import {SlowFadingAnimation} from '../../app.animations';
import { ComponentCanDeactivate } from '../../guards/pending-changes.guard';
import { Observable } from 'rxjs/Observable';
import { SwitchComponent } from '../switch/switch.component';

@Component({
  selector: 'st-event-form',
  templateUrl: './event-form.component.html',
  animations: [
    SlowFadingAnimation
  ],
  styleUrls: ['./event-form.component.scss'],
  providers: [EventPlannerService]
})
export class EventFormComponent implements OnInit, ComponentCanDeactivate {
  @ViewChild(SwitchComponent)
  private switchComponent: SwitchComponent;
  setOn() {
     this.switchComponent.setOn();
  }
  setOff() {
     this.switchComponent.setOff();
  }
  setDisabled() {
     this.switchComponent.setDisabled();
  }
  setEnabled() {
    this.switchComponent.setEnabled();
  }
...

这是其他组件(事件形式)html,我包括2个开关实例,如下所示:

...
      <div class="form-group">
        <st-switch></st-switch>
      </div>
      <div class="form-group">
        <st-switch></st-switch>
      </div>
      <button type="submit" [disabled]="eventDetailsForm.pristine" class="btn btn-success pull-right">SAVE</button>
    </form>

我希望能做什么

当事件表单中有多个开关时,如何从events-form.component访问名为setOn(),setOff的方法或者switch.component的任何其他方法? (编程)

component-nesting-layout

1 个答案:

答案 0 :(得分:0)

当你有一个独特的孩子可以观看时,@ ViewChild效果很好。如果我是你,我会使用@Output和eventEmitters来轻松区分开关。

首先,将事件发射器添加到交换机组件:

export class SwitchComponent {
    switch = new Switch();
    @Input() name = defaultName; // can be changed from parent
    @Output() change = new EventEmitter();

    constructor() { }

    toggle() {
        this.switch.state = !this.switch.state; // here's a shorthand for toggling boolean values
        this.change.emit(this.switch.state);
    }

然后在您的父模板中:

<div class="form-group">
    <st-switch [name]="switch1name" (change)=onChange('first')></st-switch>
</div>
<div class="form-group">
    <st-switch [name]="switch2name" (change)=onChange('second')></st-switch>
</div>

然后在父模型中:

onChange(switch) {
    if (switch === 'first') { 
        this.switch1name = 'newSwitchName'; // you can set any properties like this
    }
    else if (switch === 'second') { // do stuff for the second switch }
}

您可以针对不同的操作发出不同的事件,但您希望得到这个想法。这根本不需要@ViewChild。另外,您可能需要查看此文章:https://toddmotto.com/component-events-event-emitter-output-angular-2

我希望这有帮助!