2016-08-02 67 views
1

我需要一個函數來獲取特定的DIV中的所有圖像內的所有標籤,我試圖用BrowserDomAdapter但它拋出這個錯誤el.querySelector is not a function,事實上我還沒有宣佈我的組件的任何el變量角2:獲取特定的div

import { BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter'; 
... 
... 
constructor(private dom:BrowserDomAdapter){ 
} 
ngAfterContentInit(){ 
    this.lightboxImages(); 
} 
lightboxImages(){ 
    let dom = new BrowserDomAdapter(); 
    let images = dom.querySelector('img','.post-body'); 
    console.log(images); 
} 

更新

如果我有一個變量裏面的<img>標籤,我怎樣才能得到它的圖像?

export class Post{ 

    post:Post; 

    @Input() 
    set data(data:any) { 
    this.post = new Post(data); 
    this.lightboxImages(this.post.content()); 
    } 

    lightboxImages(content:any){ 
     let images = content. ??? 
     console.log(images); 
    } 
} 

回答

3

BrowserDomAdapter是不應該被使用。它僅供Angular內部使用。

我假設你想,因爲你使用ngAfterContentInit查詢兒童傳遞的元素:

@Component({ 
    ... 
    template: ` 
    ... 
    <div #wrapper> 
    <ng-content></ng-content> 
    </div> 
    ... 
` 
}) 
export class MyComponent { 
    @ViewChild('wrapper') wrapper:ElementRef; 
    ngAfterContentInit(){ 
    this.lightboxImages(); 
    } 
    lightboxImages(){ 
    let images = this.wrapper.nativeElement.querySelector('img','.post-body'); 
    console.log(images); 
    } 
} 
+0

我不能用'@ ContentChildren'這種情況? '@ContentChildren('。post-body')' –

+0

是的,你可以使用它,但是需要看看你的模板是怎麼樣的? – micronyks

+1

不,你不能在'@ContentChildren()'中使用CSS選擇器。如果你想查詢的元素有一個像'#wrapper'類似的模板變量,那麼你可以直接使用'@ContentChildren()'來使用模板變量的名字來查詢這些元素。我認爲這是不期望的,因爲它使元素使用起來更麻煩。 –