How do non-Mandarin speakers type Standard Chinese Writing System? As far as I know, people in Hong Kong speak Cantonese but use Mandarin when writing official documents or homework using Mandarin. 粤语白话字 is not allowed in such cases.

How does this work? Does this imply that to write language down in such cases need some knowledge of Mandarin(like grammar and character's semantics but not native pronunciation), like ancient Japanese people do?
Yes, Hong Kong Chinese-literate people write and have knowledge of Standard Chinese ("Mandarin") when writing documents and homework, in Traditional Chinese (as the standard characters) of course.


  No, ancient Japanese didn't work this way. Japanese people used Classical Chinese as the official writing standard, and either spoke some dialect of Middle Chinese when reciting it or (more commonly) translated it into Japanese before recitation.
  
  Only Japanese Buddhist monks had a tradition of reciting Chinese Sutras (經) in On'yomi - the result is generally incomprehensible to both Chinese and Japanese people, as can be heard here.




The written language shared across all Chinese-using regions is called 現代標準漢語 (Modern Standard Chinese; MSC). In its written form, the grammar and vocabulary is heavily based on a refined topolect originating in the area around the Beijing Imperial Court, commonly known as "Mandarin".

MSC is different from and doesn't use colloquialisms from spoken Northern Speech (北方話), which, like all other Chinese topolects, has its own quirks. If slang-heavy colloquial 北方話 is written, other regions wouldn't be able to understand it! The refined, standardised nature of written MSC means that the vocabulary and grammar are very accessible to Chinese-literate people, regardless of mother tongue.

MSC replaced Classical Chinese (文言) since the May Fourth Movement. Whereas before, 文言 was pronounced in the mother tongue of the person reciting it, now MSC is pronounced in the mother tongue. In practice, only Hong Kong and Macao recite MSC passages using non-Mandarin in a school setting, as they are the only regions where non-Mandarin (Cantonese) is the de-facto vernacular.

The May Fourth Movement affected the whole of China; even though Hong Kong was a British Colony, the Mainland was the official source of Chinese-language education. Educational materials were free-flowing into Hong Kong until 1949 when the Communists kicked the Nationalists out and the British subsequently restricted movement into Hong Kong. Thus, educational written Chinese in Hong Kong schools was based on MSC written materials from Mainland China until 1949, after which Hong Kong had to come up with its own educational materials - which were and are still based on MSC.

Please see 香港百姓是從什麼時候開始習得官話白話文的書面表達能力的呢？ - 知乎 for a bit more history.