How to create custom input component with ngModel working in angular 6?

前端 未结 5 1324
天命终不由人
天命终不由人 2020-12-12 21:00

Since I use inputs with a lot of the same directives and .css classes applyed, I want to extract the repeated code to some component like this:

  @Component(         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 21:47

    You can use shareservice which communicate between tow components without use input or output like below

    Service

    import {Injectable} from '@angular/core';
    
    @Injectable()
    export class ShareService {
       public data: string;
    
       setData(newdata : string){
           this.data = newdata;
       }
    
       clearData(){
           this.data = '';
       }
    }
    

    Component that sets the value

    export class PageA {
        constructor(private shareService: ShareService, private router: Router){
        }
        gotoPageB(){
            this.shareService.setData("Sample data");
            this.router.navigate(['pageb']);  
        }
    
    }
    

    Component that gets the value

    export class PageB {
        constructor(private shareService: ShareService){ }
    
        get somedata() : string {
          return this.shareService.data;
        }
    }
    

    The key here is to use a getter property in the component that gets the value (PageB in this example) so it is updated any time that the data service value changes.

提交回复
热议问题