Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - 从子组件到父组件的输出无法正常工作(Output from child to parent component doesn't work properly)

I want to pass data from child to parent component but it doesn't work in a proper way: function isn't invoked.

(我想将数据从子组件传递到父组件,但是它不能以适当的方式工作:未调用函数。)

    <router-outlet (activeElement)='getActive($event)'></router-outlet>
    <div class="myDIV"> 
    <button *ngFor="let i of numberOfButtons" (click)="navigate(i)"  [ngClass]="(i === active) ? 'btn active': 'btn'">{{i}}</button>
    </div>

child component ts.file

(子组件ts.file)

@Output() activeElement = new EventEmitter();
  constructor(private activatedRoute:ActivatedRoute,private getPlanets:GetPlanetsService,private router: Router, private renderer:Renderer2,private elRef: ElementRef) { 
    activatedRoute.params.subscribe(value=>{
      this.fivePlanetIndex=value.id;
      this.activeElement.emit(value.id);
    });
  }

parent component .ts file

(父组件.ts文件)

  getActive(i){
    console.log(i); //it is not invoked
  }
  ask by graluc translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Output will work by using component selector, not with router-outlet .

(Output将通过使用组件选择器而不是router-outlet起作用。)

Because router-outlet used to render multiple components and it doesn't make sense to set all Input s and Output s on there.

(因为router-outlet用来渲染多个组件,所以在此处设置所有InputOutput都没有意义。)

If you wanna use router-outlet and catch events from children components, you can use Observable s;

(如果您想使用router-outlet并从子组件中捕获事件,则可以使用Observable ;)

where child component send result and parent component subscribe to it.

(子组件发送结果,父组件订阅该结果。)

sample.service.ts

(sample.service.ts)

// you will use subject to emit event from child
subject = new Subject<any>();
// you will use observable to listen to events from parent
observable = this.subject.asObservable();

child.component.ts

(child.component.ts)

constructor(service: SampleService) {}

// instead of emit function
this.service.subject.next();

parent.component.ts

(parent.component.ts)

constructor(service: SampleService) {}

// instead of event listener 
this.service.observable.subscribe();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...