mat-menu and button in different components

后端 未结 2 1874
感情败类
感情败类 2021-02-19 08:12

I have

...

in app-save-document component and

&         


        
2条回答
  •  灰色年华
    2021-02-19 09:01

    Well, if you want to do something like this:

    
    
    
      
      
    
    

    You can code like this:

    import {Component,Input} from '@angular/core';
    import {MatMenu} from '@angular/material';
    
    @Component({
      selector: 'other-component',
      template: `
        This button is in another component:
        
      `,
    })
    export class OtherComponent {
      @Input() matMenu: MatMenu;
    }
    

    You can see the above example working at this stackblitz demo.


    Another approach

    Another approach is (I think this is what you want): your trigger button is inside the parent (but outside the child) and the menu itself is defined inside the child component.

    Parent component:

    
    
    
    export class ParentComponent {
      @ViewChild(ChildComponent) childComponentMenu: ChildComponent;
    }
    

    Child Component:

    @Component({
      selector: 'child-component',
      template: `
        
          
          
        
      `,
    })
    export class ChildComponent {
      @ViewChild(MatMenu, {static: true}) menu: MatMenu;
    }
    


    Yet Another approach

    Another approach, similar to the above one, but using template reference variables (notice the exportAs in the decorator of the child component):

    Parent component:

    
    
    
    export class ParentComponent {
    }
    

    Child Component:

    @Component({
      selector: 'child-component',
      template: `
        
          
          
        
      `,
      exportAs: 'menuInOtherComponent',
    })
    export class ChildComponent {
      @ViewChild(MatMenu, {static: true}) menu: MatMenu;
    }
    

    Stackblitz demo

提交回复
热议问题