-1

I have two components. An object will be added to an array inside Component2. In the smae method, that object has to be passed to an array inside Component1.

I have tried @Input and services, getting help from the solutions I found here. But, these are creating a new instance of the components. The array is getting reset, instead of having new object pushed into it.

What's the fix? Cannot figure out how to use @Input properly with router-outlet.

A generic solution would be very helpful. Thank you.

2
  • 1
    Share the code what you had tried so far. Commented Nov 15, 2018 at 4:55
  • please share some code so that we can help you Commented Nov 15, 2018 at 5:43

2 Answers 2

1

You can make use of component interaction via a service.

Component A:

@Component({
  selector: 'app-a',
  template: `
    <h1>A</h1>
    <p *ngFor="let item of dat">{{item}}</p>
    <button type="button" (click)="addNumber()">Add Number</button>
  `,    
})
export class AComponent implements OnInit {

  dat: Array<number> = [1, 2, 3];
  count: number;
  constructor(private service: AppService){}

  ngOnInit(){
    this.count = 3;
  }

  addNumber(){
    this.count++;
    this.dat.push(this.count);
    this.service.addNewValue(this.count);
  }
} 

Component B:

@Component({
  selector: 'app-b',
  template: `
    <h1>B</h1>
    <p *ngFor="let item of dat">{{item}}</p>
  `,    
})
export class BComponent {
  dat: Array<number> = [1, 2, 3];
  subscription: Subscription;

  constructor(private service : AppService){
    this.subscription = this.service.newValue$.subscribe((res)=>{
      this.dat.push(res);
    })
  }
} 

Service:

export class AppService {

  private newValue = new Subject<number>();
  newValue$ = this.newValue.asObservable();

  constructor(private http: HttpClient) { }

  // Service message commands
  addNewValue(value: number) {
    this.newValue.next(value);
  }
}

Demo: Stackblitz

Sign up to request clarification or add additional context in comments.

Comments

0

if you are passing data with the router, you can pass the data with NavigationExtras.

import { NavigationExtras, Router } from '@angular/router';
// all the code we know here
export class AnyComponent {

constructor(private router: Router) { }

  passData(data) {
    let navigationExtras: NavigationExtras = {
      queryParams: {
      passedData: data
      };
      this.router.navigate(['whereUGo'], navigationExtras);
  }
}

then you catch in the other component with activated route.

https://angular.io/api/router/NavigationExtras

Here is the info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.