最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 make function available in ng-content - Stack Overflow

programmeradmin1浏览0评论

I have a dropdown with a template like this:

<div class="dropdown-trigger" (click)="contentToggle()">
     <ng-content select="dropdown-trigger"></ng-content>
</div>
<div class="dropdown-content" *ngIf="showContent">
     <ng-content select="dropdown-content"></ng-content>
</div>

I'd like to be able to use contentToggle() in whatever I put in the ng-content so that I can have additional elements that can be used to close the dropdown, for example I might want a close button... What's the best way to do this?

I have a dropdown with a template like this:

<div class="dropdown-trigger" (click)="contentToggle()">
     <ng-content select="dropdown-trigger"></ng-content>
</div>
<div class="dropdown-content" *ngIf="showContent">
     <ng-content select="dropdown-content"></ng-content>
</div>

I'd like to be able to use contentToggle() in whatever I put in the ng-content so that I can have additional elements that can be used to close the dropdown, for example I might want a close button... What's the best way to do this?

Share Improve this question edited Apr 5, 2017 at 16:35 nick asked Apr 5, 2017 at 16:32 nicknick 3,7113 gold badges25 silver badges34 bronze badges 5
  • what is that you are trying to do. explain as it is unclear – Aravind Commented Apr 5, 2017 at 16:34
  • @Aravind added more detail, is that enough? – nick Commented Apr 5, 2017 at 16:35
  • this is handled by bootstrap by default. – Aravind Commented Apr 5, 2017 at 16:37
  • @Aravind I'm not using bootstrap – nick Commented Apr 5, 2017 at 16:37
  • create a plunker I will fix – Aravind Commented Apr 5, 2017 at 16:38
Add a ment  | 

2 Answers 2

Reset to default 8

This will do the trick:

<dropdown #dropdown>
  <button dropdownTrigger (click)="dropdown.toggleDropdown()">Click me</button>
</dropdown>

You just assign a local template variable to the ponent which gives you access to everything the ponent has in it. Including the function you want to call.

Note that you should/need to also change the select bits to this:

<ng-content select="[dropdownTrigger]"></ng-content>
<ng-content select="[dropdownContent]"></ng-content>

Angular allow you to do this trick, Example:

import { Component } from '@angular/core'

@Component(){...}
export class DropdownComponent {
   toggleDropdown() {...}
}

//parent.ponent.html
<dropdown-content #myDropdown>
  <a (click)="myDropdown.toggleDropdown()">Close the dropdown</a>
</dropdown-content>

If you want to get a callback to the event I remend you to read the Output Decorator

发布评论

评论列表(0)

  1. 暂无评论