Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ng-content #72

Open
deepthan opened this issue Jul 27, 2020 · 0 comments
Open

ng-content #72

deepthan opened this issue Jul 27, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

ng-content

是什么?

它是一个插槽,可以把父组件的dom元素传递到子组件中。相当于vue里的slot

如何使用

直接传递小示例

父组件有一段文本'可爱的小猫',传入子组件中

父组件ts

@Component({
  selector: 'parent',
  template: `
    <son> <p>可爱的小猫</p> </son>
  `,
})

子组件ts

@Component({
  selector: 'son',
  template: `
    <ng-content></ng-content> 
  `,
})

子组件html会以此渲染:

@Component({
  selector: 'son',
  template: `
    <p>可爱的小猫</p>
  `,
})

<ng-content></ng-content>是一个插槽,把<p>可爱的小猫</p>插入了它占的位置。

其他用法

其实和 querySelector 选取dom用法差不多。

1. 通过节点匹配

@Component({ // 父组件ts
  selector: 'parent',
  template: `
    <son> <p cat>可爱的小猫</p> </son>
  `,
})
@Component({ //子组件ts
  selector: 'son',
  template: `
    <ng-content select='p'></ng-content> 
  `,
})

2. 通过属性值匹配

@Component({ // 父组件ts
  selector: 'parent',
  template: `
    <son> <p cat>可爱的小猫</p> </son>
  `,
})
@Component({ //子组件ts
  selector: 'son',
  template: `
    <ng-content select='[cat]'></ng-content> 
  `,
})

3. 通过class匹配

@Component({ // 父组件ts
  selector: 'parent',
  template: `
    <son> <p class="cat">可爱的小猫</p> </son>
  `,
})
@Component({ //子组件ts
  selector: 'son',
  template: `
    <ng-content select='.cat'></ng-content> 
  `,
})

4. 通过id匹配

@Component({ // 父组件ts
  selector: 'parent',
  template: `
    <son> <p id="cat">可爱的小猫</p> </son>
  `,
})
@Component({ //子组件ts
  selector: 'son',
  template: `
    <ng-content select='#cat'></ng-content> 
  `,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant