在Angular 2+中,如果它还应用了Angular指令,那么如何指定本机元素应该绑定到模板变量?

时间:2017-02-01 10:59:52

标签: angular material

Angular 2+模板变量的语法如下:

<someElement #someVariable="someDirective"></someElement>

其中someElement是元素标记,someVariable是变量名称,someDirectivesomeElement上应该绑定到someVariable的指令。< / p>

如果缺少someDirective,即

<someElement #someVariable></someElement>

someElement是一个原生HTML元素,没有Angular指令,然后someVariable将绑定到该元素的ElementRef

但是当someElement 具有Angular指令时,如何重现此行为?如何指定我希望ElementRef绑定到变量而不是某些指令?据我所知,没有像

这样的语法

<someElement #someVariable="element"></someElement>

(虽然proposals exist)。

我的具体用例是我尝试获取此模板中ElementRef元素的button

<button md-raised-button #button>Click me</button>

其中md-raised-buttonAngular Material指令。但#button只是绑定到MdButton

1 个答案:

答案 0 :(得分:5)

在您的组件中,您可以使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <section class="portfolio-container"> <div id="menu-picker"> <a href="#" data-id="1" class="menu-text">Portfolio 1</a> <a href="#" data-id="2" class="menu-text">Portfolio 2</a> <a href="#" data-id="3" class="menu-text">Portfolio 3</a> </div> <!--/menu-picker--> <div id="pages"> <div class="mydivshow portfolio1"> <p>1. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo.</p> </div> <!--/portfolio-div1--> <div class="mydivhide portfolio2"> <p>2. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo.</p> </div> <!--/portfolio-div2--> <div class="mydivhide portfolio3"> <p>3. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo.</p> </div> <!--/portfolio-div3--> </div> <!--/pages--> </section> <!--/portfolio-container--> </body>阅读@ViewChild的{​​{1}}

ElementRef