从一个组件到另一个组件的绑定单击事件

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

在Angular中可以将点击事件从组件动态绑定到页面上的现有组件。为了说明,我包括了此screenshot

该应用现在由4个简单的组件组成;一个定义全局布局的shell组件,在shell组件中,我有一个标头组件(蓝色轮廓)和一个导航组件(红色轮廓)。绿色组件是当前路线加载的组件。

我正在使用简单的服务来更新导航组件,如下所示:

@Injectable({ providedIn: 'root' })
export class NavigationService {

  private titleSource = new Subject<string>();
  private actionsSource = new Subject<ActionButton[]>();
  private menuItemsSource = new Subject<MenuItem[]>();

  title = this.titleSource.asObservable();
  actions = this.actionsSource.asObservable();
  menuItems = this.menuItemsSource.asObservable();

  constructor() {
  }

  setTitle(title: string) {
    this.titleSource.next(title);
  }

  setActions(actions: ActionButton[]) {
    this.actionsSource.next(actions);
  }

  setMenuItems(menuItems: MenuItem[]) {
    this.menuItemsSource.next(menuItems);
  }
}

导航组件只是像这样使用此服务:

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html'
})
export class NavigationComponent implements OnInit {
  title: string = "";
  actions: ActionButton[] = [];
  menuItems: MenuItem[] = [];

  constructor(private navigation: NavigationService)  { 
    navigation.title.subscribe((title) => this.title = title);
    navigation.actions.subscribe((actions) => this.actions = actions);
    navigation.menuItems.subscribe((menuItems) => this.menuItems = menuItems);
  }
}

并显示如下:

<div class="navigation">
    <div *ngIf="title.length" class="navigation__title">
        <h1>{{title}}</h1>
    </div>
    <div class="navigation__menu">
        <ul>
            <li *ngFor="let menuItem of menuItems"  [routerLinkActive]="['active']">
                <a routerLink="{{menuItem.path}}">{{menuItem.title}}</a>
            </li>
        </ul>
    </div>
    <div class="navigation__actions">
      <a *ngFor="let actionButton of actions" class="btn btn--primary">{{actionButton.title}}</a>
    </div>
</div>

然后在当前激活的组件(绿色组件)中,设置标题和类似的项目

 ....

  constructor(private employeeService: EmployeeService, private navigation: NavigationService, private drawerService: NzDrawerService) { 
    navigation.setTitle('');
    navigation.setActions([
      {
        path: '',
        title: 'Add Employee'
      }
    ]);
    navigation.setMenuItems([
      {
        path: '/employees',
        title: 'Employees'
      },
      {
        path: '/teams',
        title: 'Teams'
      }
    ]);
  }
  ....

在同一活动组件中,我也定义了此方法:

  createEmployee() {
    const drawer = this.drawerService.create<CreateEmployeeComponent>({
      nzContent: CreateEmployeeComponent,
      nzClosable: false,
      nzWidth: '33%',
    });

    drawer.afterClose.subscribe(data => {
      this.loadEmployees();
    });
  }

现在我的问题是,当我单击导航组件上呈现的按钮时,是否可以以某种方式调用此方法。并从当前激活的组件中动态设置它,就像我已经为标题和导航项所做的一样]

在Angular中可以将点击事件从组件动态绑定到页面上的现有组件。为了说明这一点,我提供了此屏幕截图。该应用程序包含4个简单的组件...

angular typescript angular8 angular-services angular-components
1个回答
0
投票

您可以为此使用Object orientation

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