2017-05-23 9 views
0

私はapiから受け取ったhtml文字列を持っています。私は、画像のurlまたはimageのsrc属性だけを、angle2を使って文字列全体から選びたいと思っています。どのように私はそれについて行く必要があります..どんな助けも大いに感謝されるでしょう。Angular2のhtml DOM childNodesの属性を取得する方法

<div class="field field-name-field-image field-type-image field-label-hidden"> 
<div class="field-items"> 
    <div class="field-item even" rel="og:image rdfs:seeAlso" resource="https://www.example.com/image/image001_42.jpg?itok=RuoKJFFA"> 
     <a href="/example.com"> 
      <img typeof="foaf:Image" src="https://www.example.com/image/image001_42.jpg?itok=RuoKJFFA" width="220" height="130" alt="title here" /> 
     </a> 
     </div> 
     </div> 
     </div> 
+0

これは、あなたが角度を関与させる必要があるものではありません。私は、DocumentFragmentを作成し、必要なものを照会するのがうまくいくと思います。 'DocumentFragment'は純粋なブラウザ+ JS –

+0

です。考えていただきありがとうございます。 – Ernesto

+0

https://developer.mozilla.org/en/docs/Web/API/に乗ることができるサンプルコードを教えてください。ドキュメント/ createDocumentFragment、https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment/querySelector –

答えて

0

あなたが本当にAPI可能性が高いだけでsrc=のための文字列を解析して、二重引用符の間の値を取得し、文字列として入ってくるの呼びかけから、あなたのHTMLを取得している場合。

let fullString = `<div class="field field-name-field-image field-type-image field-label-hidden"> 
<div class="field-items"> 
    <div class="field-item even" rel="og:image rdfs:seeAlso" resource="https://www.example.com/image/image001_42.jpg?itok=RuoKJFFA"> 
     <a href="/example.com"> 
      <img typeof="foaf:Image" src="https://www.example.com/image/image001_42.jpg?itok=RuoKJFFA" width="220" height="130" alt="title here" /> 
     </a> 
     </div> 
     </div> 
     </div>`; 
     // get the start of the src 
let srcStart = fullString.indexOf('src="'); 

// get the end of the src by starting at it's position + the number of chars 
let srcEnd = (fullString.indexOf('"', srcStart + 5)); 

let srcUrl = fullString.substring(srcStart, srcEnd); 

console.log('URL', srcUrl); 

あなたは本当にあなたが持っているし、それを参照するためにViewChild()を使用しています要素を見つけ、それがAngular2にする必要がある場合:

@ViewChild(myObject) myObject: ElementRef 
let ref = myObject.nativeElement; 
+0

すばらしい..あなたのコードは働いていました。@Dennis you genuis。ありがとうございました。 – Ernesto

+0

心配はいりません!私の答えに正しい印を付けることができますか? SOの虚栄心を助けます;) –

関連する問題