Angular Material:如何从子组件导航到不同的 mat-tab 组件?

问题描述 投票:0回答:1

我有一个包含

mat-tab-group
的父组件,每个
mat-tab
是一个不同的组件。 我隐藏了
mat-tab-header
,因为我不想从标题导航,而是希望选项卡根据点击进行切换。

在我的父组件中我有:

<mat-tab-group [(selectedIndex)]="tabIndex">
    <mat-tab>
        <mm-child-one [selectTab]="selectTab"></mm-child-one>
    </mat-tab>
    <mat-tab>
        <mm-child-two></mm-child-two>
    </mat-tab>
</mat-tab-group>

还有 ts:

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

export enum InputTab {
  TAB_ONE = 0,
  TAB_TWO = 1,
}
@Component({
  selector: 'mm-input-dialog',
  templateUrl: './input-dialog.html',
  styleUrls: ['./input-dialog.sass']
})
export class InputDialog {

  public tabIndex = 0;
  public inputTab: InputTab;

  constructor() { }

  selectTab(tab: InputTab): void {
    this.tabIndex = tab;
  }
}

在我的子组件中,

selectTab
函数在单击时执行,预期的行为是导航到
TAB_ONE
并呈现组件
child-two
。这是 child-one.component.ts:

import { Component, Input } from '@angular/core';
import { InputTab } from '../input-dialog/input-dialog';

@Component({
  selector: 'mm-child-one',
  templateUrl: './child-one.component.html',
  styleUrls: ['./child-one.component.sass']
})
export class ChildOneComponent{

  constructor() { }
  @Input() selectTab: (tab: InputTab) => void;

  navigate(tab: InputTab): void {
    console.log('at least one level works');
    this.selectTab(tab);
  }

}

最后是调用导航功能的

child-one.component.html

<div class="card-wrapper">
    <mat-card (click)="navigate(1)">
        <h3>Title</h3>
        <div class="illustration"></div>
    </mat-card>
</div>

我在这里做错了什么?

我想在一个选项卡内单击导航到另一个选项卡。

angular angular-material
1个回答
1
投票

您似乎已经在父组件中定义了 selectTab 方法,但您正试图将其作为输入传递给子组件。相反,您可以在子组件中定义 selectTab 方法并向父组件发出事件以更改所选选项卡。

以下是修改代码的方法:

  1. 在您的父组件中,从
  2. 中删除 selectTab 输入
  3. 在您的子组件 (ChildOneComponent) 中,创建一个新的 EventEmitter 并定义 selectTab 方法以在调用时发出事件:

打字稿:

import { Component, EventEmitter, Output } from '@angular/core';
import { InputTab } from '../input-dialog/input-dialog';

@Component({
  selector: 'mm-child-one',
  templateUrl: './child-one.component.html',
  styleUrls: ['./child-one.component.sass']
})
export class ChildOneComponent {
  @Output() selectTab = new EventEmitter<InputTab>();

  navigate(tab: InputTab): void {
    console.log('at least one level works');
    this.selectTab.emit(tab);
  }
}

在您的父组件中,修改标签以监听子组件发出的 selectTab 事件并调用 selectTab 方法来更改选定的选项卡:

<mat-tab-group [(selectedIndex)]="tabIndex">
  <mat-tab>
    <mm-child-one (selectTab)="selectTab($event)"></mm-child-one>
  </mat-tab>
  <mat-tab>
    <mm-child-two></mm-child-two>
  </mat-tab>
</mat-tab-group>

现在,当在 ChildOneComponent 中调用导航函数时,它将使用新的 InputTab 值向父组件发出一个事件。然后父组件会将选中的选项卡更改为指定的值。

© www.soinside.com 2019 - 2024. All rights reserved.