4

How do you deal with the following situation where two components use the same selector? (removed the word "Component" to avoid clutter):

app.ts

import { Component } from '@angular/core';
import { Person as Person1 } from './person1';
import { Person as Person2 } from './person2';
@Component({
  selector: 'app',
  template: '<person1???></person1><person2???></person2>',
  directives: [Person1, Person2]
})
export class App {

}

person1.ts

import { Component } from '@angular/core';
@Component({
  selector: 'person',
  template: '<h1>Person 1</h1>'
})
export class Person {

}

person2.ts

import { Component } from '@angular/core';
@Component({
  selector: 'person',
  template: '<h1>Person 2</h1>'
})
export class Person {

}

This isn't a problem with React since you'd just use <Person1 /> and <Person2 />

2
  • why you use selector: 'person' in both cases? It will'not work because you haven't this elements (<person1> and <person1>) Commented May 25, 2016 at 18:36
  • 1
    You can add two elements with the same selector imperatively using ViewContainerRef.createComponent() like shown in stackoverflow.com/questions/36325212/… You could also add them declaratively if you wrap each of your <person> component in a different wrapper component. Commented May 25, 2016 at 19:04

1 Answer 1

1

Based on Günter Zöchbauer comment you can add a bunch of boilerplate to accomplish this and wrap the components:

app.ts

import { Component } from '@angular/core';
import { Person as Person1 } from './person1';
import { Person as Person2 } from './person2';

@Component({
  selector: 'person1',
  template: '<person></person>',
  directives: [Person1]
})
export class Person1Wrapper {

}

@Component({
  selector: 'person2',
  template: '<person></person>',
  directives: [Person2]
})
export class Person2Wrapper {

}

@Component({
  selector: 'app',
  template: '<person1></person1><person2></person2>',
  directives: [Person1Wrapper, Person2Wrapper]
})
export class App {

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

1 Comment

directives no longer supported.

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.